Java Reference
In-Depth Information
identically to method
add
(line 15). Line 17 calls
LinkedList
method
addFirst
to add
"cyan"
as the new first item in the
LinkedList
. The
add
operations are permitted because
they operate on the
LinkedList
object, not the view returned by
asList
. [
Note:
When
"cyan"
is added as the first element,
"green"
becomes the fifth element in the
LinkedList
.]
Line 20 calls the
List
interface's
toArray
method to get a
String
array from
links
. The
array is a copy of the list's elements—modifying the array's contents does
not
modify the list.
The array passed to method
toArray
is of the same type that you'd like method
toArray
to
return. If the number of elements in that array is greater than or equal to the number of ele-
ments in the
LinkedList
,
toArray
copies the list's elements into its array argument and
returns that array. If the
LinkedList
has more elements than the number of elements in the
array passed to
toArray
,
toArray
allocates a new array
of the same type it receives as an argu-
ment,
copies
the list's elements into the new array and returns the new array.
Common Programming Error 16.2
Passing an array that contains data to
toArray
can cause logic errors. If the number of
elements in the array is smaller than the number of elements in the list on which
toArray
is called, a new array is allocated to store the list's elements—
without preserving the ar-
ray argument's elements
. If the number of elements in the array is greater than the num-
ber of elements in the list, the elements of the array (starting at index zero) are overwritten
with the list's elements. Array elements that are not overwritten retain their values.
Class
Collections
provides several high-performance algorithms for manipulating collec-
tion elements. The algorithms (Fig. 16.5) are implemented as
static
methods. The meth-
ods
sort
,
binarySearch
,
reverse
,
shuffle
,
fill
and
copy
operate on
List
s. Methods
min
,
max
,
addAll
,
frequency
and
disjoint
operate on
Collection
s.
Method
Description
Sorts the elements of a
List
.
sort
Locates an object in a
List
, using the high-performance binary search algorithm
which we introduced in Section 7.15 and discuss in detail in Section 19.4.
binarySearch
Reverses the elements of a
List
.
reverse
Randomly orders a
List
's elements.
shuffle
Sets every
List
element to refer to a specified object.
fill
Copies references from one
List
into another.
copy
Returns the smallest element in a
Collection
.
min
Returns the largest element in a
Collection
.
max
Appends all elements in an array to a
Collection
.
addAll
Calculates how many collection elements are equal to the specified element.
frequency
Determines whether two collections have no elements in common.
disjoint
Fig. 16.5
|
Collections
methods.