Write a Short notes on Vectors



VECTORS

C and C++ programmers will know that generic utility functions with variable arguments can be used to pass different arguments depending upon the calling situations. Java does not support the concept of variable arguments to a function. This feature can be achieved in Java through the use of the Vector class 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 have to be homogenous. Array can be easily implemented as vector. Vectors are created like arrays as follows:

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

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

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

Vector possess a number of advantages over arrays.

1.  It is convenient to use vectors to store objects.

2. A vector can be used to store alist of objects that may vary in size.

3.  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 types in a vector; we can only store objects. Therefore, we need to convert simple tyhpes 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. Important ones are listed

Method Call and task performed

list.addElement (item) Adds the item specified to the list at the end.

list.elementAt(10) Gives the name of the 10th object.

list.size() Gives the number of objects present.

list.removeElement(item) Removes the specified item from the list.

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

list.removeAllElements() Removes all the item stored in the nth position of the list.

list.copyInto(array) Copies all items from list to array.

list.insertElementAt(item,n) Inserts the item at nth position.

Example of working with vectors:

import java.util.*;

class LanguageVector
{
public static void main(String args[])
{
Vector list=new Vector();  //creating an object for vector class
int length=args.length;

for(int i=0;i<length;i++)
{
list.addElement(args[i]);;
list.insertElementAt(”COBOL”,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]);
}
}
}

Random Posts

Post a Comment