Vector in java

Vector Class

In this tutorial, we are going to discuss Vector in java. The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is fully compatible with collections. It is found in the java.util package and implements the List interface, so we can use all the methods of the List interface here.

Vector in java
  • The underlying Data structure for the vector is resizable array or growable array.
  • Insertion order is preserved.
  • Duplicate objects are allowed.
  • ‘null’ insertion is possible.
  • Heterogeneous objects are allowed.
  • Best choice if the frequent operation is retrieval.
  • Worst choice if the frequent operation is insertion or deletion in the middle.
  • Vector class implemented serializable, cloneable and RandomAccess Interfaces.
  • Every method present in Vector is synchronized and hence Vector is Thread safe.
Vector specific methods
To add objects
1. add(Object o);-----Collection
2. add(int index,Object o);-----List
3. addElement(Object o);-----Vector 
To remove elements
1. remove(Object o);--------Collection
2. remove(int index);--------------List
3. removeElement(Object o);----Vector
4. removeElementAt(int index);-----Vector
5. removeAllElements();-----Vector
6. clear();-------Collection 
To get objects
1. Object get(int index);---------------List
2. Object elementAt(int index);-----Vector
3. Object firstElement();--------------Vector
4. Object lastElement();---------------Vector 
Other methods
1. int size();//How many objects are added
2. int capacity();//Total capacity
3. Enumeration elements();
Constructors

1. Vector v=new Vector();

  • Creates an empty Vector object with default initial capacity 10.
  • Once Vector reaches its maximum capacity, then a new Vector object will be created with double capacity. That is “newcapacity=currentcapacity*2”
  1. Vector v=new Vector(int initialcapacity);
  2. Vector v=new Vector(int initialcapacity, int incrementalcapacity);
  3. Vector v=new Vector(Collection c);
package com.ashok.collections.linkedlist;

import java.util.Vector;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyLinkedList {
   public static void main(String[] args) {
      Vector vector = new Vector();
      System.out.println(vector.capacity());// 10
      for (int i = 1; i <= 10; i++) {
         vector.addElement(i);
      }
      System.out.println(vector.capacity());// 10
      vector.addElement("Ashok");
      System.out.println(vector.capacity());// 20
      System.out.println(vector);// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Ashok]
   }
}
Vector in java

Scroll to top