Java Reference
In-Depth Information
4. static class ProductComparator implements Comparator<Product> {
5. public int compare(Product a, Product b) {
6. return (int) (a.price - b.price);
7. }
8. }
9.
10. public static void main(String [] args) {
11. List<Product> list = new ArrayList<Product>();
12. Product toFind = new Product(“shirt”, 29.99, 101);
13. list.add(toFind);
14. list.add(new Product(“shoes”, 150.00, 202));
15. list.add(new Product(“tie”, 12.50, 303));
16. ProductComparator pc = new ProductComparator();
17. Collections.sort(list, pc);
18. for(Product p : list) {
19. System.out.println(p.description + “ “ + p.price);
20. }
21. int index = Collections.binarySearch(list, toFind, pc);
22. System.out.println(“Index of shirt is “ + index);
23. }
24. }
The ProductComparator class sorts Product objects in ascending order by price . Three
Product objects are added to the ArrayList from line 11, and then the list is sorted
by price on line 17. Line 21 searches for the “shirt” product, and the resulting index is
printed on line 22. The output of the previous program is
tie 12.5
shirt 29.99
shoes 150.0
Index of shirt is 1
Because the Product objects are sorted by price, the shirt is second in the list, so its
index is 1 .
Use the binarySearch methods to fi nd a specifi c element in a list. Remember that a
list must be sorted fi rst before invoking binarySearch or the result is undefi ned. Use the
Collections class to sort and search lists. The next section discusses the sorting and
searching of arrays in Java using the Arrays class.
Search WWH ::




Custom Search