Vector Class Simplified in Java

In general the quantity of creating new objects is only known during runtime.Since we don't know it during compile time, we can not create named handle like an array. To create dynamic and hold objects java provides container classes like vector. The Vector class implements a grow-able array objects like ArrayList.Like Array it contains components that can be accessed using an integer index.With vector we can create a generic dynamic array that can hold objects of any type and any number.The size of a vector can grow or shrink as needed to accommodate additions  of items  and removal of items.Each Vector tries to optimize the storage management by maintaining the capacity and the capacity increment.The capacity is always as least as large as the Vector size.It is in general larger because as components are added to Vector, the Vector's storage increases in chunks(equal to the size of the capacity increment).An application can increase the capacity of a vector before increasing a large number of components. This phenomenon reduces the amount of incremental reallocation.
The structure of the Vector Class is given as :


public class java.util.Vector extends java.lang.Object implements java.lang.Cloneable{
//Member elements:
protected incrementCount
// the number of valid components in the vector
protected Object elementData[];
//the array buffer into which teh components of the vector are stored.the length of this array buffer is the current capacity of the vector.
//Constructors:
public Vector();
//creates an empty vector
public Vector(int initialCapacity);
//creates an empty vector with the initial capacity provided
public Vector(int initialCapacity,int capacityIncrement);
//creates an empty vector with the initial capacity and capacity increment provided
//Methods:
public final void addElement(Object obj);
//adds the element obj at the end of the vector object
public final void copyInto(Object anArray[]);
//copies all elements from a vector to Array
public final void ensureCapacity(int minCapacity);
public final void insertElementAt(Object obj,int index);
//inserts the specified element at the given index of the vector
public final void removeAllElements();
//removes all elements from the vector
public final void removeElementAt(int index);
//removes the element object present in the index location from the vector.Index must be in between 0 to size-1
public final void setSize(int newSize);
//sets the size of the vector.If there were more than newSize elements in the vector, the extra elements are removed. If there were fewer elements in the vector the remaining spaces are filled with null.
public final void setElementAt(Object obj,int index);
public final int capacity();
public final int indexOf(Object element);
public final int indexOf(Object element,int index);
public final int lastIndexOf(Object element);
public final int lastIndexOf(Object element,int index);
public final int size();
//returns the elements present in the vector
public final Object elementAt(int index);
//returns the element object present in the index of the vector.
public final Object firstElement();
//returns the first element of the vector
public final Object lastElement();
//returns the last element of the vector
public final void trimToSize();
public final boolean isEmpty(); 
//checks if the vector is empty.If it empty returns true else return false
public final boolean removeElement(Object obj); 
//removes the specified item from the vector
public final boolean contains(Object element)
public Object clone();
public final Enumeration element();
public final String toString();
}
 
To overcome an size issue of array the best alternative is to create and use of Vector.Once it reaches to the limit,we run out of space and we create a new array and copy the content from old array to the new array.Vector class does the same.Since it gives size flexibility,a vector is less efficient than array in terms of time.
The way we can create vectors are as follows:


Vector myVector1=new Vector();
Vector myVector2=new Vector(5);
 
A vector declared without specifying size can accommodate an unknown number of items in it. Even if the size is specified we can add different items beyond the size of the vector.

A vector is an unbounded Array but we can put any kind of objects into a vector using addElement() method and fetch using elementAt() method.It is effective when we don't know in Advance what size our array will become.
An example of Vector class is given below:


//create a vector
Vector myFruits=new Vector();
//add elements to vector
myFruits.addElement("Banana");
myFruits.addElement("Apple");
myFruits.addElement("Grape");
//get elements from vector
String value=(String)myFruits.elementAt(i);
i belongs to 0 to myFruits.Size()-1
 


Advantage:
  1. It is very convenient to use and put standard objects into a container.
  2. A vector can be used to a list of objects (they may vary in size).
  3. We can add and delete objects from the Vector as and when required.


Disadvantage:
  1. Vector can not directly store simple data type , we can store only objects so we need to convert the data type into Objects before storing them.
  2. As in one place we insert objects and in other part of the code we get the objects from the Vector,it is very tough to determine if a bad object is inserted into the Vector.And we we only know the bad type of object in form of an exception.This makes the code very painful to find of issues and bug prone.
  3. We need to do the object casting to the appropriate type before working with them


Vector,stack,hashtable all deal with the Objects as if they had no specific type(they treat them as type Object,the root class of all classes in java). This works fine from one standpoint: we need to build only one container and java objects will go into the container.(Except primitives, we need Wrapper classes for that).
Here is an example how Vector can create issue while holding different data types into it:

class Pen{
private int penNumber;
Pen(int i)
{
penNumber=i;
}
void print(){
System.out.println("Pen #"+penNumber);
}
}
class Pencil{
private int pencilNumber;
Pencil(int i)
{
pencilNumber=i;
}
void print(){
System.out.println("Pencil#"+pencilNumber);
}
}
public class PenPencilTest{
public static void main(String args[])
{

Vector pens=new Vector();
//insert elements in the vector
for(int j=0;j<10;j++)
pens.addElement(new Pen(j));
pens.addElement(new Pencil(10));
//get elements from vector
for(int k=0;kj<pens.size;k++)
((pens)pens.elementAt(k)).print();
//Pencil is detected at runtime
}
}
Classes Pen and Pencil are distinct,they have nothing common other than the fact that they both are objects.(If we don't say from which class they are inherited from automatically they inherit from Object).As vector class can hold Objects so we can put Pencil into the Pen vector.
Now using elementAt(index) method ,we get back a handle to an Object which we need to cast to appropriate type Pen or Pencil by putting in a cast expression (type) before calling a method.Otherwise we will get a syntax error. Again in the run time as wrong casting has happened to Pencil (we tried to cast to Pen), we will get an exception.
Vector Class Simplified in Java Vector Class Simplified in Java Reviewed by Animesh Chatterjee on September 20, 2018 Rating: 5

No comments:

Powered by Blogger.