这个压缩包里的都是超级经典的java例子
源代码在线查看: coll_insertinlist.htm
Inserting an Element into a Sorted List (Java Developers Almanac Example)
The Java Developers Almanac 1.4
Order this book from Amazon.
google_ad_client = "pub-6001183370374757";
google_ad_width = 120;
google_ad_height = 600;
google_ad_format = "120x600_as";
google_ad_channel = "4777242811";
google_ad_type = "text_image";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "6666CC";
google_color_url = "6666CC";
google_color_text = "000000";
//-->
Home
>
List of Packages
>
java.util
[51 examples]
>
Sorted Collections
[6 examples]
e362. Inserting an Element into a Sorted List
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
// 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");
}
Related Examples
e358.
Creating a Sorted Set
e359.
Sorting an Array
e360.
Finding an Element in a Sorted Array
e1075.
Inserting an Element into a Sorted Array
e361.
Finding an Element in a Sorted List
See also:
Arrays
Bits
Collections
Dates
Hash Tables
Lists
Property Files
Sets
Time
Timers
© 2002 Addison-Wesley.