Skip to content

Java Vector Class

  • by

Vector Class :

  1.  The underlying data structure is a resizable array or growable array.
  2.  Insertion order is preserved.
  3.  Duplicates objects are allowed.
  4.  Heterogeneous objects are allowed.
  5.  Null insertion is possible.
  6.  Vector implements Serializable, Cloneable interfaces and Random Access interfaces.
  7.  Vector is the best choice if our frequent operation is retrieval.
  8.  Linked List is the worst choice if our frequent operation is retrieval operation.
  9.  Most of the methods in vector objects are Synchronized. Hence vector object is Thread-Safe.

Methods:

For add object:-

  • add(Object o)
  • add(int index, Object o)
  • addElement(Object o)

For removing objects:-

  • remove(Object o)
  • removeElement(int index, Object o)
  • remove(int index)
  • removeElement(int index)
  • clear()
  • removeAllElements()

For retrieval elements:-

  • Object get(int index)
  • Object elementAt(int index)
  • Object firstElement()
  • Object LastElement()

For other methods:-

  • int size() //Current Size
  • int capacity(int index) // Total Capacity
  • Enumeration elements() // Retrieve elements one by one

CONSTRUCTORS

  • Vector V = new Vector();
  • Creates an empty vector object with default initial capacity 10, Once Vector reaches its max capacity.

New Capacity = 2* Current Capacity

  • Vector v = new Vector(int initialCapacity);
  • Vector v = new Vector(int initialCapacity, int increamentalCapacity)
  • Vector v = new Vector(Collection c );//creates an equivalent vector object for the given collection

Example of Vector :

import java.util.Vector;

public class VectorDemo{
	
	public static void main(String arg[]){
		
		Vector v  =  new  Vector();
		System.out.println(v.capacity());//[10]
		
		for(int i=0; i<10; i++){
			v.addElement(i);
		}
		System.out.println(v.capacity());//[10]
		v.addElement("A");
		
		System.out.println(v.capacity());//[20]
		System.out.println(v);
		
	}
}

Output :

10
10
20
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A]

Difference between ArrayList and Vector

Leave a Reply

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