digitization, transformation, binary

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 a vector.

The Vector class implements a variable-length array that can hold any kind of object. Like an array, the elements in a Vector are accessed with an integer index. However, unlike an array, the size of a Vector can grow and shrink as needed to accommodate a changing number of objects. Vector provides methods to add and remove elements, as well as ways to search for objects in a Vector and iterate through all of the objects.

The Vector class implements grow-able array objects like ArrayList but for objects. 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 storage management by maintaining the capacity and capacity increment. The capacity is always at 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).

The initial capacity of a Vector specifies how many objects it can contain before more space must be allocated. The capacity increment specifies how much more space is allocated each time the Vector needs to increase its capacity. We can fine-tune the performance of a Vector by adjusting the initial capacity and 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,java.io.Serializable{
//Member elements:
protected int capacityIncrement;
protected int incrementCount;// the number of valid components in the vector
protected Object elementData[];//the array buffer into which the 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 synchronized void addElement(Object obj);//adds the element obj at the end of the vector object and increment the size by 1.
public final synchronized void copyInto(Object anArray[]);//copies all elements from a vector to Array
public final synchronized void ensureCapacity(int minCapacity);//Sets the specified minimum capacity to the size of the Vector.
public final synchronized void insertElementAt(Object obj,int index);//inserts the specified element at the given index of the vector
public final synchronized void removeAllElements();//removes all elements from the vector
public final synchronized 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 synchronized 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 synchronized void setElementAt(Object obj,int index);//Replaces the element at the specified index with specified element.
public final int capacity();//returns the current capacity of the Vector
public final int indexOf(Object element);
public final synchronized int indexOf(Object element,int index);
public final int lastIndexOf(Object element);
public final synchronized int lastIndexOf(Object element,int index);
public final int size();//returns the size of the vector.
public final synchronized Object elementAt(int index);//returns the element object present in the index of the vector.
public final synchronized Object firstElement();//returns the first element of the vector
public final synchronized Object lastElement();//returns the last element of the vector
public final synchronized void trimToSize();
public final boolean isEmpty(); //checks if the vector is empty.If it empty returns true else return false
public final synchronized boolean removeElement(Object obj); //removes the specified item from the vector
public final boolean contains(Object element);//returns true if the specified object is present in the Vector.
public final boolean contains(Collection c);//returns true if all the elements are present in the specified collection in the vector.
public final Object get(int index);//Returns the object which is available in the specified index.
public synchronized Object clone();
public final synchronized Enumeration element();
public final synchronized String toString();//returns a String representation of the Vector.
} 

The details of the class structure are given as follows:

protected int capacityIncrement;

protected int capacityIncrement represents the amount by which the internal array grows when more space is needed. If the value is 0, the internal array doubles in size when more space is needed.

protected int elementCount;

protected int elementCount represents the count of how many objects are contained in this Vector.

protected Object[] elementData;

protected Object[] elementData represents the array that holds the contents of this Vector.

public Vector();

public Vector() constructor creates an empty Vector with the default capacity of 10 and the default capacity increment of 0.

public Vector(int initialCapacity);

public Vector(int initialCapacity) constructor creates an empty Vector with the given capacity and the default capacity increment of 0.

READ  Class ParsePosition in Java

Parameter
initialCapacity – The initial capacity of the Vector.

public Vector(int initialCapacity, int capacityIncrement);

public Vector(int initialCapacity, int capacityIncrement) constructor creates an empty Vector with the given capacity and capacity increment.

Parameter
initialCapacity – The initial capacity of the Vector.
CapacityIncrement – The amount to increase the capacity when more space is needed.

public final synchronized void addElement(Object obj);

public final synchronized void addElement(Object obj) method adds the given object to this Vector as its last element and increases its size by 1. The capacity of the Vector is increased if its size becomes greater than its capacity. Any kind of object can be added to a Vector.

Parameter
obj – The object to be added.

public final int capacity();

public final int capacity() method returns the size of the internal array of this Vector.

This method returns The capacity of this Vector.

public synchronized Object clone();

public synchronized Object clone() method creates a copy of this Vector and returns it.

This method returns A copy of this Vector.

public final boolean contains(Object elem);

public final boolean contains(Object elem) method determines whether or not the given object is contained in this Vector.

This method returns true if the given object is contained in this Vector; false otherwise.

Parameter
elem – The object to be found.

public final synchronized void copyInto(Object[] anArray);

public final synchronized void copyInto(Object[] anArray) method copies the object references in this Vector to the given array.

Parameter
anArray – The array to be filled.

public final synchronized Object elementAt(int index);

public final synchronized Object elementAt(int index) method returns the object at the given index in this Vector.

This method returns the object at the position given by the index.

Parameter
index – The index of the object to be returned.

public final synchronized Enumeration elements();

public final synchronized Enumeration elements() method returns an Enumeration that iterates through the objects in this Vector.

This method returns The objects in this Vector as an Enumeration.

public final synchronized void ensureCapacity(int minCapacity);

public final synchronized void ensureCapacity(int minCapacity) method expands the internal array, if necessary, to make the capacity of the Vector at least minCapacity.

Parameter
minCapacity – The minimum new capacity.

public final synchronized Object firstElement();

public final synchronized Object firstElement() method returns the object at index 0 in this Vector.

This method returns the first object in this Vector.

public final int indexOf(Object elem);

public final int indexOf(Object elem) method returns the index of the first occurrence of the given object in this Vector.

This method returns the index of the given object or -1 if it cannot be found.

Parameter
elem – The object to be found.

public final synchronized int indexOf(Object elem, int index);

public final synchronized int indexOf(Object elem, int index) method returns the index of the next occurrence of the given object in this Vector after the given index.

READ  Java Documentation-JavaDoc Concept Simplified in Java

This method returns the index of the next occurrence of the given object after the specified index or -1 if it cannot be found.

Parameter
elem – The object to be found.
index – The starting index.

public final synchronized void insertElementAt(Object obj, int index);

public final synchronized void insertElementAt(Object obj, int index) method inserts the given object at the given index in this Vector. Each object in the Vector with an index greater than or equal to index is shifted upward in the Vector, so that it has an index of one greater than it did previously.

Parameter
obj – The object to be inserted.
index – The index at which to insert the object.

public final boolean isEmpty();

public final boolean isEmpty() method returns a boolean value that indicates whether or not the Vector is empty.

This method returns true if there are no objects in the Vector; false otherwise.

public final synchronized Object lastElement();

public final synchronized Object lastElement() method returns the last object in this Vector.

This method returns the last object in this Vector.

public final int lastIndexOf(Object elem);

public final int lastIndexOf(Object elem) method returns the index of the last occurrence of the given object in this Vector.

This method returns the index of the given object or -1 if it cannot be found.

Parameter
elem – The object to be found.

public final synchronized int lastIndexOf(Object elem, int index);

public final synchronized int lastIndexOf(Object elem, int index) method returns the index of the last occurrence of the given object in this Vector before the given index. In other words, the method searches backwards from index for the next occurrence.

This method returns the index of the last occurrence of the given object before the specified index or -1 if it cannot be found.

Parameter
elem – The object to be found.
index – The starting index.

public final synchronized void removeAllElements();

public final synchronized void removeAllElements() method removes all of the objects from this Vector, but does not change its capacity or capacity increment.

public final synchronized boolean removeElement(Object obj);

public final synchronized boolean removeElement(Object obj) method searches for the first occurrence of the given object in this Vector and removes it. If the object is found, each object in the Vector with an index greater than or equal to the index of the removed object is shifted downward in the Vector, so that it has an index of one less than it did previously.

This method returns true if the given object is found and removed; false otherwise.

Parameter
obj – The object to be removed.

public final synchronized void removeElementAt(int index);

public final synchronized void removeElementAt(int index) method removes the object at the given index from this Vector. Each object in the Vector with an index greater than or equal to index is shifted downward in the Vector, so that it has an index of one less than it did previously.

Parameter
index – The index of the object to be removed.

public final synchronized void setElementAt(Object obj, int index);

public final synchronized void setElementAt(Object obj, int index) method puts the given object at the given index in this Vector, replacing the object that was previously there.

Parameter
obj – The object to be put in the Vector.
index – The index at which to put the object.

public final synchronized void setSize(int newSize);

public final synchronized void setSize(int newSize) method sets the size (not the capacity) of this Vector. If the new size is bigger than the current size, null elements are added to the end of the Vector. If the new size is smaller than the current size, elements are discarded from index newSize to the end of the Vector.

Parameter
newSize – The new size.

public final int size();

public final int size() method returns the number of objects contained in this Vector.

This method returns the size of this Vector.

public final synchronized String toString();

public final synchronized String toString() method returns a string representation of this Vector. The string includes every object that is contained in the Vector, so the string returned by toString() can be quite long.

READ  When Frame.pack method Can Be Used While Designing Swing Desktop Based Application?

This method returns a string that represents this Vector.

public final synchronized void trimToSize();

public final synchronized void trimToSize() method sets the capacity of this Vector equal to its size. We can use this method to minimize the storage space used by the Vector, but any subsequent calls to addElement() or insertElement() forces the Vector to allocate more space.

Apart from these Vector class also has inherited methods from class- Object. They are as follows:

  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)
To overcome a size issue of the array the best alternative is to create and use Vector. Once it reaches the limit, we run out of space and we create a new array and copy the content from the old array to the new array. The vector class does the same. Since it gives size flexibility, a vector is less efficient than an 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
//or
Iterator it=myFruits.iterator();
while(it.hashNext())
{
System.out.println(it.next());
}
 

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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here