Powered by Blogger.

Enumerate Vector using java.util.Enumeration

>> Sunday, October 17, 2010

Enumerate through a Vector using Java Enumeration Example.This Java Example shows how to enumerate through elements of a Vector using Java Enumeration.

Enumeration provides two methods to enumerate through the elements. It's hasMoreElements method returns true if there are more elements to enumerate through otherwise it returns false. Its nextElement method returns the next element in enumeration.

static ArrayList list(Enumeration e) method of Collections class. This method returns the ArrayList containing the elements returned by specified Enumeration object in order they are returned.

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.Vector;

   public class CreateArrayListFromEnumerationExample {
   public static void main(String[] args) {
   //create a Vector object
   Vector v = new Vector();
   //Add elements to Vector

   v.add("A");
   v.add("B");
   v.add("D");
   v.add("E");
   v.add("F");
   
   System.out.println("Vector contains : " + v);
   //Get Enumeration over Vector
   Enumeration e = v.elements();
   //Create ArrayList from Enumeration of Vector
   ArrayList aList = Collections.list(e);
   System.out.println("Arraylist contains : " + aList);

  }
 }

Output is:

Vector Contains : [A, B, D, E, F]
Arraylist contains : [A, B, D, E, F]

Reference Books:

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.