Java Reference
In-Depth Information
The output for
list1
is
[white, black, green, blue]
. The
copy
method performs a
shallow copy: only the references of the elements from the source list are copied.
You can use the
nCopies(int n, Object o)
method to create an immutable list that
consists of
n
copies of the specified object. For example, the following code creates a list with
five
Calendar
objects.
nCopies
List<GregorianCalendar> list1 = Collections.nCopies
(
5
,
new
GregorianCalendar(
2005
,
0
,
1
));
The list created from the
nCopies
method is immutable, so you cannot add, remove, or
update elements in the list. All the elements have the same references.
You can use the
fill(List list, Object o)
method to replace all the elements in the
list with the specified element. For example, the following code displays
[black, black,
black]
.
fill
List<String> list = Arrays.asList(
"red"
,
"green"
,
"blue"
);
Collections.fill(list,
"black"
);
System.out.println(list);
You can use the
max
and
min
methods for finding the maximum and minimum elements
in a collection. The elements must be comparable using the
Comparable
interface or the
Comparator
interface. For example, the following code displays the largest and smallest
strings in a collection.
max
and
min
methods
Collection<String> collection = Arrays.asList(
"red"
,
"green"
,
"blue"
);
System.out.println(Collections.max(collection));
System.out.println(Collections.min(collection));
The
disjoint(collection1, collection2)
method returns
true
if the two collections
have no elements in common. For example, in the following code,
disjoint(collection1,
collection2)
returns
false
, but
disjoint(collection1, collection3)
returns
true
.
disjoint
method
Collection<String> collection1 = Arrays.asList(
"red"
,
"cyan"
);
Collection<String> collection2 = Arrays.asList(
"red"
,
"blue"
);
Collection<String> collection3 = Arrays.asList(
"pink"
,
"tan"
);
System.out.println(Collections.disjoint(collection1, collection2));
System.out.println(Collections.disjoint(collection1, collection3));
The
frequency(collection, element)
method finds the number of occurrences of the
element in the collection. For example,
frequency(collection, "red")
returns
2
in the
following code.
frequency
method
Collection<String> collection = Arrays.asList(
"red"
,
"cyan"
,
"red"
);
System.out.println(Collections.frequency(collection,
"red"
));
20.17
✓
✓
Are all the methods in the
Collections
class static?
Check
20.18
Point
Which of the following static methods in the
Collections
class are for lists, and
which are for collections?
sort, binarySearch, reverse, shuffle, max, min, disjoint, frequency
20.19
Show the output of the following code:
import
java.util.*;
public class
Test {
public static void
main(String[] args) {
Search WWH ::
Custom Search