Tutorials

Java Collection Programs


Vector Example


As we know Vetcor is a legacy class and is now obsolete so its use is not encouraged.

We will see a simple example to know how it works.

In this chapter, our task is:

  • create a vector
  • add elements to the vector
  • traverse the vector, and 
  • print the vector

Example: Create and traverse Vector using Enumeration


package Vector;

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

public class VectorExample {

      public static void main(String[] args) {

         //create Vector
          Vector vec = new Vector();
      
          //add elements to Vector
           vec.add(1);
           vec.add(22);
           vec.add(33);
           vec.add("numbers");

          //Traverse vector using Enumeration
            Enumeration e = Collections.enumeration(vec);

            while(e.hasMoreElements())

               System.out.println(e.nextElement());

            }

}

OUTPUT:

1
22
33
numbers

 

Use Generics in Vector

We can apply Generics on the Vector to restric the type of object that the Vector supports.

For example, 

Vector<String> vec = new Vector<String>();

 

Once you replace ⇒ Vector vec = new Vector(); with above:

  • You will be able to add only String objects in the created Vector 'vec
  • If you add object of other type like Integer, Float, etc, you will get compiler error.

Example


package Vector;

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

public class VectorExample {

      public static void main(String[] args) {

            //create Vector
            Vector vec = new Vector();
         
            //add elements to Vector
            vec.add("Shweta");
            vec.add("Puja");
            vec.add("Kavya");
            vec.add("numbers");

            //Traverse vector using Enumeration
            Enumeration e = Collections.enumeration(vec);

            while(e.hasMoreElements())

                  System.out.println(e.nextElement());

           }

}

Since Enumeration is mostly used to traverse legacy classes like Vector, HashTable etc. so we are showing example with Enumeration only.

Before we proceed for HashSet examples, lets say for one more time - "Vector is a legacy class and its use is discouraged"

 

 



Please Share this page
Views : 74
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!