/* related posts with thumb nails */


Vector class is contained in the java.util package. This class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number. The objects do not have to be homogeneous. Arrays can be easily implemented as vectors. The variable-arguments feature can also be achieved in Java through the use of the Vector. Vectors are created like arrays as follows:

Vector list = new Vector ( ); // declaring without size

Vector list = new Vector (3); // declaring with size

A vector can be declared without specifying any size explicitly. A vector without size can accommodate an unknown number of items. Even, when a size is specified, this can be overlooked and a different number of items may be put into the vector. But, in contrast, an array must always have its size specified.

Vectors have a number of advantages over arrays.

· It is convenient to use vectors to store objects.

· A vector can be used to store a list of objects that may vary in size.

· We can add and delete objects from the list as and when required.

A major constraint in using vectors is that we cannot directly store simple data type in a vector; we can only store objects. Therefore, we need to convert simple types to objects. This can be done using the wrapper classes. The vector class supports a number of methods that can be used to manipulate the vectors created.


Adds the item specified to the list at the end


Gives the name of the nth object


Gives the number of objects present


Removes the specified item from the list


Removes the item stored in the nth position of the list

removeAllElements( )

Removes all the elements in the list


Copies all items from list to array

InsertElementAt (Item, n)

Inserts the item at nth position

Example: The following program demonstrates Vector and some of its methods.

import java.util.*;

class VectorTest


public static void main(String as[])


Vector v1=new Vector(10);






System.out.println("Number of Elements:"+v.size());

System.out.println("Vector Elements:"+v1);



/* Output: */

Number of Elements: 3

Vector Elements: [Apple, Banana, Sapota]

Related Topics:


Post a Comment