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

          今天早上起來讀書,發現如下的一種方法來對向一個已經排好序的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());
          ??}
          ?}
          }

          posted on 2006-09-24 08:35 張氏兄弟 閱讀(365) 評論(0)  編輯  收藏

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


          網站導航:
           
          主站蜘蛛池模板: 古丈县| 金溪县| 五指山市| 无锡市| 武穴市| 沛县| 安仁县| 滦平县| 达州市| 太和县| 增城市| 荃湾区| 河津市| 贵州省| 府谷县| 渭源县| 石屏县| 梧州市| 文昌市| 揭西县| 兴安县| 遂昌县| 英超| 德庆县| 凤阳县| 卓尼县| 洛阳市| 浮梁县| 车致| 金沙县| 龙游县| 宁强县| 九台市| 霍林郭勒市| 阿尔山市| 新乐市| 乐陵市| 榕江县| 河北区| 赤城县| 阳城县|