Tutorials

# 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();

//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();

//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"