Java Reference
In-Depth Information
// We'll see these utility methods later Be aware that there are
// some subtleties to watch out for when using them
Collection
<
String
>
d
=
Arrays
.
asList
(
"one"
,
"two"
);
Collection
<
String
>
e
=
Collections
.
singleton
(
"three"
);
// Add elements to a collection. These methods return true
// if the collection changes, which is useful with Sets that
// don't allow duplicates.
c
.
add
(
"zero"
);
// Add a single element
c
.
addAll
(
d
);
// Add all of the elements in d
// Copy a collection: most implementations have a copy constructor
Collection
<
String
>
copy
=
new
ArrayList
<
String
>(
c
);
// Remove elements from a collection.
// All but clear return true if the collection changes.
c
.
remove
(
"zero"
);
// Remove a single element
c
.
removeAll
(
e
);
// Remove a collection of elements
c
.
retainAll
(
d
);
// Remove all elements that are not in e
c
.
clear
();
// Remove all elements from the collection
// Querying collection size
boolean
b
=
c
.
isEmpty
();
// c is now empty, so true
int
s
=
c
.
size
();
// Size of c is now 0.
// Restore collection from the copy we made
c
.
addAll
(
copy
);
// Test membership in the collection. Membership is based on the equals
// method, not the == operator.
b
=
c
.
contains
(
"zero"
);
// true
b
=
c
.
containsAll
(
d
);
// true
// Most Collection implementations have a useful toString() method
System
.
out
.
println
(
c
);
// Obtain an array of collection elements. If the iterator guarantees
// an order, this array has the same order. The array is a copy, not a
// reference to an internal data structure.
Object
[]
elements
=
c
.
toArray
();
// If we want the elements in a String[], we must pass one in
String
[]
strings
=
c
.
toArray
(
new
String
[
c
.
size
()]);
s
a
// Or we can pass an empty String[] just to specify the type and
// the toArray method will allocate an array for us
strings
=
c
.
toArray
(
new
String
[
0
]);
Remember that you can use any of the methods shown here with any
Set
,
List
, or
Queue
. These subinterfaces may impose membership restrictions or ordering con‐
straints on the elements of the collection but still provide the same basic methods.