Java Reference
In-Depth Information
value. Method binarySearch determines this negative value by first calculating the inser-
tion point and making its sign negative. Then, binarySearch subtracts 1 from the inser-
tion point to obtain the return value, which guarantees that method binarySearch returns
positive numbers (>= 0) if and only if the object is found. If multiple elements in the list
match the search key, there's no guarantee which one will be located first. Figure 16.12
uses method binarySearch to search for a series of strings in an ArrayList .
1
// Fig. 16.12: BinarySearchTest.java
2
// Collections method binarySearch.
3
import java.util.List;
4
import java.util.Arrays;
5
import java.util.Collections;
6
import java.util.ArrayList;
7
8
public class BinarySearchTest
9
{
10
public static void main(String[] args)
11
{
12
// create an ArrayList<String> from the contents of colors array
13
String[] colors = { "red" , "white" , "blue" , "black" , "yellow" ,
14
"purple" , "tan" , "pink" };
15
List<String> list =
16
new ArrayList<>(Arrays.asList(colors));
17
18
Collections.sort(list); // sort the ArrayList
19
System.out.printf( "Sorted ArrayList: %s%n" , list);
20
21
// search list for various values
22
printSearchResults(list, "black" ); // first item
23
printSearchResults(list, "red" ); // middle item
24
printSearchResults(list, "pink" ); // last item
25
printSearchResults(list, "aqua" ); // below lowest
26
printSearchResults(list, "gray" ); // does not exist
27
printSearchResults(list, "teal "); // does not exist
28
}
29
30
// perform search and display result
31
private static void printSearchResults(
32
List<String> list, String key)
33
{
34
int result = 0 ;
35
36
System.out.printf( "%nSearching for: %s%n" , key);
37
result = Collections.binarySearch(list, key);
38
39
if (result >= 0 )
40
System.out.printf( "Found at index %d%n" , result);
41
else
42
System.out.printf( "Not Found (%d)%n" ,result);
43
}
44
} // end class BinarySearchTest
Fig. 16.12 | Collections method binarySearch . (Part 1 of 2.)
 
Search WWH ::




Custom Search