Enumeration to ArrayList with list(Enumeration)

Enumeration to ArrayList with list(Enumeration)

After seeing the interoperability between legacy and collections classes with "Enumerated Collection with enumeration()", let us see one more interoperability feature with list(Enumeration e). With this Enumeration object, legacy classes (JDK 1.0 DS are known as legacy classes) can be converted into ArrayList. For example, the Vector elements can be converted into ArrayList elements.

Following is the method signature

  • static ArrayList list(Enumeration e): With this method, the Enumeration object e containing elements can be converted into an ArrayList. That is, vector elements can be converted into ArrayList through Enumeration. The method returns an object of ArrayList; again interoperability between collection classes and legacy classes.
Example on Enumeration to ArrayList with list(Enumeration)


Enumeration to ArrayList with list(Enumeration)
Output screenshot on Enumeration to ArrayList with list(Enumeration)

Vector vect = new Vector();
vect.addElement(10);
vect.add(50);

A Vector object vect is created and added with elements using addElement() and add() methods. add() method belongs to Collection interface (other way, collection framework) and how a legacy class like Vector can make use of this method? It is again interoperability between legacy classes and collection classes. The Vector implements List interface (List implements Collection interface). So now, Vector can make use of all the methods of Collection interface and List interface.

Enumeration e = vect.elements();
ArrayList myList = Collections.list(e);

We know earlier in "Vector Retrieval", the elements() method of Vector returns an object of Enumeration. The Enumeration object e contains all the elements of vect. This object passed to list() method. The list() method returns an object of ArrayList, myList. Now myList contains all the elements of vect. With myList, we can use Iterator and ListIterator to print the elements.

Leave a Reply

Your email address will not be published. Required fields are marked *