Vector
,
Hashtable
,
array, and
Enumeration
. In this section, you'll learn how to transform old collections to the Java
Collections Framework collections and vice versa.
Suppose the old API returns an array of objects and the new
API requires a Collection
. The Collections Framework
has a convenience implementation that allows an array of objects
to be viewed as a List
. You use
Arrays.asList
to pass an array to any method requiring a Collection
or a List
.
Foo[] result = oldMethod(arg); newMethod(Arrays.asList(result));
Vector
or a Hashtable
,
you have no work to do at all because Vector
was retrofitted
to implement the List
interface, and Hashtable
was retrofitted to implement Map
. Therefore, a Vector
may be passed directly to any method calling for a Collection
or a List
.
Vector result = oldMethod(arg); newMethod(result);
Hashtable
may be passed directly to any method
calling for a Map
.
Hashtable result = oldMethod(arg); newMethod(result);
Enumeration
that represents a collection of objects. The Collections.list
method translates an Enumeration
into a Collection
.
Enumeration e = oldMethod(arg); newMethod(Collections.list(e));
Suppose the new API returns a Collection
,
and the old API requires an array of Object
.
As you're probably aware, the Collection
interface
contains a toArray
method designed expressly for this situation.
Collection c = newMethod(); oldMethod(c.toArray());
String
(or another type) instead of an array of Object
?
You just use the other form of toArray
— the one that
takes an array on input.
Collection c = newMethod(); oldMethod((String[]) c.toArray(new String[0]));
Vector
, the standard collection
constructor comes in handy.
Collection c = newMethod(); oldMethod(new Vector(c));
Hashtable
is handled analogously.
Map m = newMethod(); oldMethod(new Hashtable(m));
Enumeration
?
This case isn't common, but it does happen from time to time, and the
Collections.enumeration
method was provided to handle it. This is a static factory method that takes a Collection
and returns an Enumeration
over the elements of the Collection
.
Collection c = newMethod(); oldMethod(Collections.enumeration(c));