Java Reference
In-Depth Information
Self-Test Exercises
4. Can an object that instantiates the
HashSet<T>
class contain multiple copies of
some element?
5. Suppose you want to define a class that orders its elements like a
List<T>
but does not
allow multiple occurrences of an element like a
Set<T>
. Would it be better to make it
a derived class of the
ArrayList<T>
class or a derived class of the
HashSet<T>
class?
Differences Between
ArrayList<T>
and
Vector<T>
For most purposes,
ArrayList<T>
and
Vector<T>
are equivalent. There are only minor
differences between the classes. The methods that are in both classes are given in Display
16.7. The class
Vector<T>
has more methods that
ArrayList<T>
does not have and that
are not given in Display 16.7. However, most of the extra methods are little more than
alternate names for methods that are in both
ArrayList<T>
and
Vector<T>
. None of the
methods in
Vector<T>
do anything that cannot easily be done with an
ArrayList<T>
.
The class
ArrayList<T>
is reputed to be more efficient than
Vector<T>
. The biggest dif-
ference between these two classes is that
ArrayList<T>
is newer than
Vector<T>
and was
created as part of the Java collection framework, whereas
Vector<T>
is an older class that
was retrofitted with extra method names to make it fit into the collection framework.
You are encouraged to use
ArrayList<T>
rather than
Vector<T>
. However, a lot of exist-
ing code uses
Vector<T>
, so you should be familiar with
Vector<T>
.
1
Nonparameterized Version of the Collection Framework
★
Before version 5.0, Java did not have type parameters. So, the collection framework
consisted of ordinary classes and interfaces, such as
Collection
,
List
,
ArrayList
, and
so forth, all of which had no type parameters. Although this older collection frame-
work has been supplanted by the new, generic version, the old version's classes and
interfaces, without type parameters, are still in the standard libraries and in a lot of
older code. There is no longer any need for the older classes and interfaces that do not
have type parameters. They can sometimes be harder to use and are less versatile than
the new, generic classes with type parameters. You should not use the older classes and
interfaces without type parameters. However, you will often see them used in older
code. When reading older code, you will not go too far wrong in thinking of
Collection
as meaning
Collection<Object>
,
ArrayList
as meaning
ArrayList<Object>
,
and so forth. This is not, strictly speaking, correct. For example, the classes
ArrayList
and
ArrayList<Object>
are not the same, but they are very similar.
1
The biggest difference between
Vector<T>
and
ArrayList<T>
classes is that
Vector<T>
objects are
synchronized
while
ArrayList<T>
objects are not. However, synchronization is a topic that we do not
cover and that is not relevant to the kinds of programming we are doing.