Vector In Java


  • The underlying data structure is re-sizable array or growable array.
  • Insertion order is preserved.
  • Duplicate objects are allowed
  • Null insertion is possible.
  • Heterogeneous objects are allowed.
  • Implements serializable, cloneable & Random Access Interfaces,
  • Best suitable if our frequent operation is retrieval & worst choice if our frequent operation is insertion or deletion in the middle.
  • Every method in vector is synchronized. Hence vector object is thread safe.

Constructors of Vector:-


  1. Vector v = new vector();
  • Creates an empty object with default initial capacity IO.
  • Once vector reaches its max. capacity a new vector object will be created with double capacity

New capacity = 2 * Current capacity

 

2. Vector v = new vector (int initialcapacity);

3 .Vector v = new vector (int initialcapacity, int incrementalcapicity);

4. Vector v = new vector (collection c);


Vector Specific methods :


  • To add objects
  1. Add(object o)
  2. Add(int index, object o)
  3. AddElement(object obj)
  • To remove elements or objects
  1. Remove(object o)
  2. RemoveElement(object o)
  3. Remove(int index)
  4. removeElementAt(int index)
  5. clear()
  6. removeAllElements()

 

  • To retrieve elements
  1. Get(int index)
  2. elementAt(int index)
  3. firstElement();
  4. LastElement();

 

  • Other methods
  1. Int size();
  2. Int capacity();
  3. Enumeration elements();

Example of Vector:-


Import java.util.*;

Class Demo

{

public static void main(String[] arg)

{

Vector v = new vector r();

System.out.println(v.capacity());

For (int i = 1; k = 10, i = ++)

{

v.addElement(i);

}

System.out.println(v.capacity());

v.addElement(“A”);

System.out.println(v.capacity());

System.out.println(v);

}

}





		
	

Leave a Reply

Your email address will not be published. Required fields are marked *