Java Reference
In-Depth Information
25. System.out.println(“Index of milk is “ + index);
26. }
27. }
A breakdown of the
ProductArraySearch
program follows:
1.
Line 4 declares a
Comparator
named
DescriptionSorter
that sorts
Product
objects in
lexicographical order of the
description
string.
2.
Line 12 fills the
products
array with four
Product
objects.
3.
Line 20 sorts the
products
array using the
DescriptionSorter
comparator. The
for
loop on line 21 prints out the sorted array.
4.
Line 24 searches the
products
array for the
“milk”
product, which appears at the end
of the array.
5.
Line 25 prints out the value of
index
.
The output of the program is
bread 1.95
butter 2.75
eggs 4.0
milk 2.95
Index of milk is 3
Because
“milk”
is at the end of the array, its index is
3
. Notice that the products are
sorted in alphabetical order by description. Use the generic version of
binarySearch
when
you search an array sorted with a
Comparator
object.
Summary
This chapter covered the “Collections and Generics” objectives of the SCJP exam. The
goal of this chapter was to discuss the details of using the Java Collections Framework, a
collection of classes and interfaces in the
java.util
package that implement common data
structures like lists, maps, and sets. The collection's classes and interfaces use generics,
which provide a compile-time type safety for simplifying the use of collections.
The
Collection
interface is the parent interface of
List
,
Set
, and
Queue
. The map
data structures implement the
Map
interface. A list is an ordered collection of elements
that allows duplicate entries. The
List
implementations include
ArrayList
,
LinkedList
,
Vector
, and
Stack
. A set is a collection that does not allow duplicate entries. The
Set
implementations are
HashSet
,
LinkedHashSet
, and
TreeSet
. A queue is a collection
that orders its elements in a specifi c order for processing. The
Queue
implementations
include
LinkedList
,
PriorityQueue
, and
ArrayDeque
. A map is a collection that maps
keys to values, with no duplicate keys allowed. The
Map
implementations are
HashMap
,
LinkedHashMap
, and
TreeMap
.
Search WWH ::
Custom Search