Tutorials

Java Collection Framework


Java Vector


Vector is an obsolete class in java and it should not be used while programming. We are adding this topic for knowledge purpose only.

Vector belongs to java.util package. Vector is a class that extends AbstractList and implements List interface, RandomAccess interface, Serializable interface and Cloneable interface.

 

Declaration of Vector class


public class Vector extends AbstractList implements List , RandomAccess, Serializable, Cloneable 

Key features of Vector

  • It also implements grow able array of objects.
  • The elements in vector can be accessed using integer index just as we do in array.
  • Vector is synchronized and thus should be preferred over ArrayList if thread-safety is concern of the developer. 
  • Due to synchronized nature, it does not allow multiple threads to access and modify itself concurrently. If one thread has access to the vector then other thread wanting to access and operate on it must wait for its turn until the vector is released by the thread in action.
  • On other hand, this synchronized nature affects Vector’s performanceSo ArrayList is preferred over Vector if performance is to be considering factor.

Create Vector in java

We can use any of the following constructors to create vector in java:

  • Vector myVector = new Vector();
  • Vector myVector = new Vector(Collection c);
  • Vector myVector = new Vector( (int initialCapacity);
  • Vector myVector = new Vector(int initialCapacity, int capacityIncrement);

Simple example on Vector

package Vector;

import java.util.Vector;

public class VectorExample {

    public static void main(String[] args) {
      //create Vector
      Vector vec = new Vector();

      //add elements to Vector
      vec.add(1);
      vec.add(22);
      vec.add(33);
      vec.add("numbers");

      System.out.println(vec);

    }

}

OUTPUT:

[1, 22, 33, numbers]

 

Now let’s look at different ways in which you can use the Vector that you created.

 

Vector operations

  • Sort the elements in vector
  • Search element in vector
  • Copy element of vector to another vector
  • Remove element from vector
  • Remove all elements from the vector
  • Remove element from a particular index in vector

Traverse Vector

  • Traverse vector using Iterator
  • Traverse vector using ListIterator
  • Traverse Vector using Enumeration

Convert

  • Vector to ArrayList
  • Vector to Array
  • Vector to LinkedList

 

 



Please Share this page
Views : 101
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!