Java Reference
In-Depth Information
List
<
Integer
>
primes
=
new
ArrayList
<
Integer
>();
List
<
Integer
>
readonly
=
Collections
.
unmodifiableList
(
primes
);
// We can modify the list through primes
primes
.
addAll
(
Arrays
.
asList
(
2
,
3
,
5
,
7
,
11
,
13
,
17
,
19
));
// But we can't modify through the read-only wrapper
readonly
.
add
(
23
);
// UnsupportedOperationException
The
java.util.Collections
class also defines methods to operate on collections.
Some of the most notable are methods to sort and search the elements of
collections:
Collections
.
sort
(
list
);
// list must be sorted first
int
pos
=
Collections
.
binarySearch
(
list
,
"key"
);
Here are some other interesting
Collections
methods:
// Copy list2 into list1, overwriting list1
Collections
.
copy
(
list1
,
list2
);
// Fill list with Object o
Collections
.
fill
(
list
,
o
);
// Find the largest element in Collection c
Collections
.
max
(
c
);
// Find the smallest element in Collection c
Collections
.
min
(
c
);
Collections
.
reverse
(
list
);
// Reverse list
Collections
.
shuffle
(
list
);
// Mix up list
It is a good idea to familiarize yourself fully with the utility methods in
Collections
and
Arrays
as they can save you from writing your own implementation of a com‐
mon task.
Special-case collections
In addition to its wrapper methods, the
java.util.Collections
class also defines
utility methods for creating immutable collection instances that contain a single ele‐
ment and other methods for creating empty collections.
singleton()
,
singleton
List()
, and
singletonMap()
return immutable
Set
,
List
, and
Map
objects that con‐
tain a single specified object or a single key/value pair. These methods are useful
when you need to pass a single object to a method that expects a collection.
The
Collections
class also includes methods that return empty collections. If you
are writing a method that returns a collection, it is usually best to handle the no-
values-to-return case by returning an empty collection instead of a special-case
value like
null
:
Set
<
Integer
>
si
=
Collections
.
emptySet
();
List
<
String
>
ss
=
Collections
.
emptyList
();
Map
<
String
,
Integer
>
m
=
Collections
.
emptyMap
();