Java Reference
In-Depth Information
The
LinkedList
class also implements
Queue
. It provides unbounded FIFO order‐
ing, and insertion and removal operations require constant time.
LinkedList
allows
null
elements, although their use is discouraged when the list is being used as a
queue.
There are two other
Queue
implementations in the
java.util
package.
Priority
Queue
orders its elements according to a
Comparator
or orders
Comparable
elements
according to the order defined by their
compareTo()
methods. The head of a
Priori
tyQueue
is always the smallest element according to the defined ordering. Finally,
ArrayDeque
is a double-ended queue implementation. It is often used when a stack
implementation is needed.
The
java.util.concurrent
package also contains a number of
BlockingQueue
implementations, which are designed for use in multithreaded programing style;
advanced versions that can remove the need for synchronized methods are avail‐
able.
Utility Methods
The
java.util.Collections
class is home to quite a few static utility methods
designed for use with collections. One important group of these methods are the
collection
wrapper
methods: they return a special-purpose collection wrapped
around a collection you specify. The purpose of the wrapper collection is to wrap
additional functionality around a collection that does not provide it itself. Wrappers
exist to provide thread-safety, write-protection, and runtime type checking. Wrap‐
per collections are always
backed by
the original collection, which means that the
methods of the wrapper simply dispatch to the equivalent methods of the wrapped
collection. This means that changes made to the collection through the wrapper are
visible through the wrapped collection and vice versa.
The first set of wrapper methods provides threadsafe wrappers around collections.
Except for the legacy classes
Vector
and
Hashtable
, the collection implementations
in
java.util
do not have
synchronized
methods and are not protected against
concurrent access by multiple threads. If you need threadsafe collections and don't
mind the additional overhead of synchronization, create them with code like this:
List
<
String
>
list
=
Collections
.
synchronizedList
(
new
ArrayList
<
String
>());
Set
<
Integer
>
set
=
Collections
.
synchronizedSet
(
new
HashSet
<
Integer
>());
Map
<
String
,
Integer
>
map
=
Collections
.
synchronizedMap
(
new
HashMap
<
String
,
Integer
>());
A second set of wrapper methods provides collection objects through which the
underlying collection cannot be modified. They return a read-only view of a collec‐
tion: any attempt to change the content of the collection results in an
Unsupported
OperationException
. These wrappers are useful when you must pass a collection to
a method that must not be allowed to modify or mutate the content of the collection
in any way:
s
a