Java Reference
In-Depth Information
Sorted ArrayList: [black, blue, pink, purple, red, tan, white, yellow]
Searching for: black
Found at index 0
Searching for: red
Found at index 4
Searching for: pink
Found at index 2
Searching for: aqua
Not Found (-1)
Searching for: gray
Not Found (-3)
Searching for: teal
Not Found (-7)
Fig. 16.12
|
Collections
method
binarySearch
. (Part 2 of 2.)
Lines 15-16 initialize
list
with an
ArrayList
containing a copy of the elements in
array
colors
.
Collections
method
binarySearch
expects its
List
argument's elements to
be sorted in
ascending
order, so line 18 uses
Collections
method
sort
to sort the list. If the
List
argument's elements are
not
sorted, the result of using
binarySearch
is
undefined
. Line
19 outputs the sorted list. Lines 22-27 call method
printSearchResults
(lines 31-43) to
perform searches and output the results. Line 37 calls
Collections
method
binarySearch
to search
list
for the specified
key
. Method
binarySearch
takes a
List
as the first argument
and an
Object
as the second argument. Lines 39-42 output the results of the search. An
overloaded version of
binarySearch
takes a
Comparator
object as its third argument, which
specifies how
binarySearch
should compare the search key to the
List
's elements.
Class
Collections
also provides the methods
addAll
,
frequency
and
disjoint
.
Collec-
tions
method
addAll
takes two arguments—a
Collection
into which to
insert
the new
element(s) and an array that provides elements to be inserted.
Collections
method
fre-
quency
takes two arguments—a
Collection
to be searched and an
Object
to be searched
for in the collection. Method
frequency
returns the number of times that the second ar-
gument appears in the collection.
Collections
method
disjoint
takes two
Collection
s
and returns
true
if they have
no elements in common
. Figure 16.13 demonstrates the use
of methods
addAll
,
frequency
and
disjoint
.
1
// Fig. Fig. 16.13: Algorithms2.java
2
// Collections methods addAll, frequency and disjoint.
3
import
java.util.ArrayList;
4
import
java.util.List;
5
import
java.util.Arrays;
6
import
java.util.Collections;
Fig. 16.13
|
Collections
methods
addAll
,
frequency
and
disjoint
. (Part 1 of 2.)