今天早上起來(lái)讀書(shū),發(fā)現(xiàn)如下的一種方法來(lái)對(duì)向一個(gè)已經(jīng)排好序的list中插入一個(gè)新值,并且使其處于合適的位置。真所謂知之方曉簡(jiǎn)單!所有的說(shuō)明和版權(quán)信息都放在注視里了。
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>
?* 因?yàn)槠鋵?shí)用故而記錄在此。 本例子是為了,往一個(gè)已經(jīng)排序好的list中插入一個(gè)新值,并且使其處于合適的位置。
?* 二分查找法不但能夠找出已經(jīng)存在的元素的位置,更能夠用來(lái)確定不存在元素的應(yīng)該在的位置。<br>
?* 計(jì)算方法如下:insert-index = (-return-value)-1 <br>
?* 原來(lái)的說(shuō)經(jīng)如下: 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());
??}
?}
}
posted on 2006-09-24 08:35
張氏兄弟 閱讀(362)
評(píng)論(0) 編輯 收藏