Inserting an Element into a Sorted List

Inserting an Element into a Sorted List

今天早上起来读书,发现如下的一种方法来对向一个已经排好序的list中插入一个新值,并且使其处于合适的位置。真所谓知之方晓简单!所有的说明和版权信息都放在注视里了。
package com.epl.javaalmanac;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 本例子翻译自http://www.javaalmanac.com/egs/java.util/coll_InsertInList.html?l=new<br>
 * 因为其实用故而记录在此。 本例子是为了,往一个已经排序好的list中插入一个新值,并且使其处于合适的位置。
 * 二分查找法不但能够找出已经存在的元素的位置,更能够用来确定不存在元素的应该在的位置。<br>
 * 计算方法如下:insert-index = (-return-value)-1 <br>
 * 原来的说经如下: This example demonstrates how to determine the index at which an
 * element should be inserted into a sorted list. Although binarySearch() is
 * used to locate existent elements, it can also be used to determine the insert
 * index for non-existent elements. Specifically, the insertion index is
 * computed in the following way: insert-index = (-return-value)-1
 *
 * @author hongzhi
 *
 */
public class InsertSortedList {
 public static void main(String[] args) {

  // Create a list with an ordered list of items

  List sortedList = new LinkedList();
  sortedList.addAll(Arrays.asList(new String[] { "ant", "bat", "cat",
    "dog" }));

  // Search for the non-existent item
  int index = Collections.binarySearch(sortedList, "cow"); // -4

  // Add the non-existent item to the list
  if (index < 0) {
   sortedList.add(-index - 1, "cow");
  }

  for (Object sortedElement : sortedList) {
   System.out.println(sortedElement.toString());
  }
 }
}

你可能感兴趣的:(Inserting an Element into a Sorted List)