Java Reference
In-Depth Information
13. System.out.print(i + “ “);
14. }
15. System.out.println();
16. int index = Collections.binarySearch(list, new Integer(5));
17. if(index >= 0) {
18. System.out.println(“5 found at index “ + index);
19. } else {
20. System.out.println(“5 not found”);
21. }
The
Integer
class implements
Comparable
, and the method call on line 16 invokes the
Comparable
version of the
binarySearch
method. The value of
index
is the location in
list
where one of the
5
s appears, or a negative value if
list
does not contain a
5
. Here is a
sample output of the previous statements:
0 0 0 1 1 2 3 3 3 5 5 5 5 5 6 8 8 9 9 9
5 found at index 9
If more than one element is found, the index returned is for one of the elements, but
there is no guarantee as to which one.
The following example demonstrates the other version of
binarySearch
that uses a
Comparator
object. Use the
Comparator
version of
binarySearch
when the elements in the
list do not implement the
Comparable
interface. For example, suppose we have a list of
Product
objects based on the
Product
class from earlier in this chapter:
public class Product {
String description;
double price;
int id;
public Product(String d, double p, int i) {
description = d;
price = p;
id = i;
}
//remainder of class definition...
}
A
Comparator
object is required to sort and search a list of
Product
objects, as
demonstrated by the following program. Study the code and see if you can determine its
result:
1. import java.util.*;
2.
3. public class ProductSearch {
Search WWH ::
Custom Search