这个压缩包里的都是超级经典的java例子
源代码在线查看: coll_findinarray.htm
Finding an Element in a Sorted Array (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]
e360. Finding an Element in a Sorted Array
// Create an array with an ordered list of strings
String[] sortedArray = new String[]{"ant", "bat", "cat", "dog"};
// Search for the word "cat"
int index = Arrays.binarySearch(sortedArray, "cat"); // 2
// Search for a non-existent element
index = Arrays.binarySearch(sortedArray, "cow"); // -4
This example also works if the element is a primitive type.
// Create an array with an ordered list of numbers
int[] sortedIntArray = new int[]{1, 2, 3, 5, 7};
// Search for 6
index = Arrays.binarySearch(sortedIntArray, 6); // -5
A negative return value indicates that the element is not in the list.
However, the actual return value can be used to determine where that
non-existent element should be inserted in the list if that were desired;
see e361 Inserting an Element into a Sorted Array.
Related Examples
e358.
Creating a Sorted Set
e359.
Sorting an Array
e361.
Inserting an Element into a Sorted Array
e362.
Finding an Element in a Sorted List
e363.
Inserting an Element into a Sorted List
See also:
Arrays
Bits
Collections
Dates
Hash Tables
Lists
Property Files
Sets
Time
Timers
© 2002 Addison-Wesley.