Program to access the Vector class in Java

Vectors are another form of Arrays in Java. The difference between array and vector is that Vector is a generic dynamic array that can hold any number of objects. The vector class is defined in the special package and that is java.util package.

import java.util.*;

class vect

{

public static void main(String aa[])

{

try

{

Vector vec21=new Vector(8,5); //vector are created by using new keyword

int i;

System.out.print('\n'+"Capacity of vector is=");

int t1=vec21.capacity();   //returns the size of the vector

System.out.println('\n'+t1+'\n');

System.out.println('\n'+"Object in vector are:");

for(i=0;i<10;i++)

{

vec21.addElement(aa[i]);   //adds an object to the vectors

String s=(String)vec21.elementAt(i);   /*retrieves the vector object,which is stored at the specified   location*/

System.out.print(" "+s);

}

vec21.addElement("ob11");   //object(ob11) add at the end of the vector

String s=(String)vec21.elementAt(10);

System.out.println('\n'+s);

vec21.addElement("ob12");

int t2=vec21.capacity();

System.out.print('\n'+"current capacity after adding to object is :"+t2);

System.out.println('\n'+"after adding objects size :"+vec21.size());

vec21.insertElementAt("ob8",8);   //add the object(ob8) at location 8

System.out.println('\n'+"object in vector are:");

for(i=0;i<vec21.size();i++)

{

String s2=(String)vec21.elementAt(i);

System.out.print(" "+s2);

}

/*displaying the first and last object of vector*/

System.out.print('\n'+"1E-------="+(String)vec21.firstElement());  

System.out.print('\n'+"lastttt-----="+(String)vec21.lastElement());  

vec21.removeAllElements(); //removing the contents of vector

System.out.print('\n'+" after remove size ="+vec21.size());

System.out.print('\n');

}

catch(Exception e)

{

System.out.println(e);

System.exit(-1);

}

}

}

Vector in Java

Explaination…..

This shows the working of Vector class in Java. An object of the Vector class is created with the initial size, 8 and incremented by 5 using its constructor. The objects in the vector are entered by user and these objects are displayed on the screen by using for loop.

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @