Java Reference
In-Depth Information
elements in a
List
with a specified value. The
fill
operation is useful for reinitializing a
List
.
Method
copy
takes two arguments—a destination
List
and a source
List
. Each
source
List
element is copied to the destination
List
. The destination
List
must be at
least as long as the source
List
; otherwise, an
IndexOutOfBoundsException
occurs. If the
destination
List
is longer, the elements not overwritten are unchanged.
Each method we've seen so far operates on
List
s. Methods
min
and
max
each operate
on any
Collection
. Method
min
returns the smallest element in a
Collection
, and
method
max
returns the largest element in a
Collection
. Both of these methods can be
called with a
Comparator
object as a second argument to perform
custom comparisons
of
objects, such as the
TimeComparator
in Fig. 16.9. Figure 16.11 demonstrates methods
reverse
,
fill
,
copy
,
max
and
min
.
1
// Fig. 16.11: Algorithms1.java
2
// Collections methods reverse, fill, copy, max and min.
3
import
java.util.List;
4
import
java.util.Arrays;
5
import
java.util.Collections;
6
7
public class
Algorithms1
8
{
9
public static void
main(String[] args)
10
{
11
// create and display a List<Character>
12
Character[] letters = {
'P'
,
'C'
,
'M'
};
13
List<Character> list = Arrays.asList(letters);
// get List
14
System.out.println(
"list contains: "
);
15
output(list);
16
17
// reverse and display the List<Character>
18
Collections.reverse(list);
// reverse order the elements
19
System.out.printf(
"%nAfter calling reverse, list contains:%n"
);
20
output(list);
21
22
// create copyList from an array of 3 Characters
23
Character[] lettersCopy =
new
Character[
3
];
24
List<Character> copyList = Arrays.asList(lettersCopy);
25
26
// copy the contents of list into copyList
27
Collections.copy(copyList, list);
28
System.out.printf(
"%nAfter copying, copyList contains:%n"
);
29
output(copyList);
30
31
// fill list with Rs
32
Collections.fill(list,
'R'
);
33
System.out.printf(
"%nAfter calling fill, list contains:%n"
);
34
output(list);
35
}
36
37
// output List information
38
private static void
output(List<Character> listRef)
39
{
Fig. 16.11
|
Collections
methods
reverse
,
fill
,
copy
,
max
and
min
. (Part 1 of 2.)