In addition to supporting the use of the old collection
classes within the new Collections Framework, there is also
support for using the new framework and still using libraries
that only support the original collections. You can easily
convert from Collection
to array, Vector
, or Enumeration
,
as well as from Map
to Hashtable
.
There are two ways to go from Collection
to array,
depending upon the type of array you need. The simplest way
involves going to an Object
array. In addition, you can
also convert the collection into any other array of objects.
However, you cannot directly convert the collection into an array
of primitives, as collections must hold objects.
To go from a collection to an Object[]
, you use the toArray()
method of Collection
:
Collection collection = ...;
Object array[] = collection.toArray();
The toArray()
method is overridden to accept an array
for placing the elements of the collection: toArray(Object
array[])
. The datatype of the argument determines the type
of array used to store the collection and returned by the
method. If the array isn't large enough, a new array of the
appropriate type will be created.
Collection collection = ...;
int size = collection.size();
Integer array[] = collection.toArray(new Integer[size]);
To go from Collection
to Vector
, the Vector
class now includes a constructor that accepts a Collection
.
As with all these conversions, if the element in the original
conversion is mutable, then no matter from where it is retrieved
and modified, it's changed everywhere.
Dimension dims[] = {new Dimension (0,0),
new Dimension (0,0)};
List list = Arrays.asList(dims);
Vector v = new Vector(list);
Dimension d = (Dimension)v.get(1);
d.width = 12;
Going from Collection
to Enumeration
is much
easier than going from Enumeration
to Collection
.
The Collections
class includes a static method to do the
conversion for you:
Collection collection = ...;
Enumeration enum = Collections.enumeration(collection);
The conversion from Map
to Hashtable
is
similar to the conversion from Collection
to Vector
: just pass the
new framework class to the constructor. After the conversion,
changing the value for the key in one does not alter the value
for the key in the other.
Map map = ...;
Hashtable hashtable = new Hashtable(map);