隨筆-60  評論-138  文章-1  trackbacks-0

          今天早上起來讀書,發(fā)現(xiàn)如下的一種方法來對向一個已經(jīng)排好序的list中插入一個新值,并且使其處于合適的位置。真所謂知之方曉簡單!所有的說明和版權(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>
          ?* 因為其實(shí)用故而記錄在此。 本例子是為了,往一個已經(jīng)排序好的list中插入一個新值,并且使其處于合適的位置。
          ?* 二分查找法不但能夠找出已經(jīng)存在的元素的位置,更能夠用來確定不存在元素的應(yīng)該在的位置。<br>
          ?* 計算方法如下:insert-index = (-return-value)-1 <br>
          ?* 原來的說經(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 張氏兄弟 閱讀(365) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 麟游县| 平定县| 太原市| 天柱县| 六枝特区| 岳池县| 二连浩特市| 甘泉县| 鹤庆县| 徐州市| 日喀则市| 沅江市| 兰坪| 四子王旗| 平舆县| 莲花县| 襄城县| 沅江市| 中牟县| 招远市| 衡山县| 监利县| 衡水市| 本溪| 长乐市| 瓦房店市| 凉城县| 深州市| 宝兴县| 泸州市| 桦甸市| 南木林县| 信阳市| 榆社县| 富锦市| 景泰县| 新泰市| 元朗区| 婺源县| 阿克苏市| 濮阳市|