Vector in Java

Vector

Vector class can be used to create a generic dynamic array known as Vector that can hold objects of any type and any number. The object do not have to be homogeneous(same type).In Vector we use java.util package.

Array can be easily implemented as vector. Vector are created like Array as:

Without Size……….Vector v=new Vector();

WithSize……………..Vector v1=new Vector(3);

 

Vector can be declared without specifying any size because this removes the limitation of an array, there is no need to declare the size like array. A Vector can support any number of items. The main advantage in using Vector is that we cannot directly store simple data type to objects. The Vector classes support a number of methods that can be used to manipulate the Vector created.

Vector Methods…..

Vector v=new Vector();

METHODS

1)v.addElements(item)--------Adds the items specified to the list(v) at the end

2)v.elementAt(10)--------------Gives the name of the 10th object

3)v.size()-------------------------Gives the number of objects present

4)v.removeElement(item)---Removes the specified item from the list(v)

5)v.removeElementAt(n)----Removes the item stored in the nth position of the list

6)v.removeAllElements()---Removes all the elements in the list(v)

7)v.copyInto(array)---------Copies all items from list to array

8)v.insertElementAt(item, n)---Insert the item at nth position

 

//Working with Vector and array

Example....

import java.util.*;

class vec

{

public static void main(String aa[])

{

Vector list=new Vector();

int len=aa.length;

for(int i=0;i<len;i++)

{

list.addElement(aa[i]);

}

list.insertElementAt(“C++”,2);

int size=list.size();

String listarray[]=new String[size];

list.copyInto(listarray);

System.out.println(‘list of languages”);

for(int i=0;i<size;i++)

{

System.out.println(listarray[i]);

}

}

}

Output are

javac vec.java

java vec   Ada Basic C C# Java

List of Languages

Ada

Basic

C++

C

C#

Java

About Us

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