Java Reference
In-Depth Information
To add a constant to an existing set, you use the
add()
method:
options.add(READ);
This adds the
StandardOpenOption.READ
constant to
options
.
The static
copyOf()
method returns a set that is the copy of its argument. The static
allOf()
method
returns a set that contains all of the constants of the enumeration type you specify as the argument. For ex-
ample:
EnumSet<StandardOpenOption> optionsCopy = EnumSet.copyOf(options);
EnumSet<StandardOpenOption> allOptions = EnumSet.allOf(StandardOpenOption.class);
The
optionsCopy
variable references a new set identical to
options
. The
allOptions
variable referen-
ces a set containing all the constants from the
StandardOpenOption
enumeration.
Next, I'll present a collection class, which you will note is close to the notion of an array, as you've now
become very familiar with arrays.
ARRAY COLLECTION CLASSES
There are two collection classes that emulate arrays:
Vector<T>
and
ArrayList<T>
. Both types define a
sequence collection of elements of any type
T
. They work rather like an array, but with the additional feature
that they can grow automatically when you need more capacity. They also implement the
List<T>
interface,
so you can also access the contents of containers of these types as a list.
These collection classes are similar in function and operation. They have the same base class and imple-
ment the same set of interfaces, so understanding the differences between them is useful.
•
Vector<T>
is synchronized so it is safe for concurrent use by more than one thread.
Ar-
rayList<T>
is not synchronized so you should not allow it to be accessed by more than one
thread. You can convert an
ArrayList<T>
into a synchronized list using the static
synchron-
izedList()
method in the
Collections
class.
• You can specify how a
Vector<T>
object should increase its capacity when it is necessary whereas
with an
ArrayList<T>
you cannot. You can have some control over how an
ArrayList<T>
in-
creases in capacity by using its
ensureCapacity()
method that sets a given capacity.
• You can discover the current capacity of a
Vector<T>
by calling its
capacity()
method. You
have no way to know the current capacity of an
ArrayList<T>
unless you have set its capacity
explicitly.
•
ArrayList<T>
is faster in general than a
Vector<T>
because it does not include the overhead
for synchronized operation. However, beware of default increments in capacity with an
Ar-
rayList<T>
.
I describe how you use array collection classes in the context of the
Vector<T>
class. However, except
where noted, the methods and usage are the same with the
ArrayList<T>
class.