Java Vector - Vector in Java - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Monday, March 13, 2017

Java Vector - Vector in Java

What is Vector in Java?

Vector implements List interface . It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legacy methods that duplicate the functionality of methods defined by the Collections Framework. Vector also maintain insertion order, but it is rarely used in non-thread environment as it is synchronized and due to which it gives poor performance in searching, adding, delete and update of its elements.

Here is the topic that will cover in this post.

  1. Vector class Diagram
  2. Vector class Declaration
  3. Vector features
  4. Vector constructors
  5. Vector class Methods
  6. Example
  7. Iterate or Traverse over Vector

Java Vector class Diagram

Java Vector class Declaration

Vector extends AbstractList and implements List and RandomAccess interface. It is a generic class that has this declaration:

public class Vector<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

Here, K specifies the type of keys, and V specifies the type of values.

Java Vector features

  1. Java Vector inherits AbstractList class.
  2. Java Vector implements List and RandomAccess interface.
  3. Java Vector permits null elements.
  4. Java Vector internally uses dynamic array to store elements.
  5. Java Vector maintain an insertion order of elements.
  6. The iterators returned by this class's iterator() iterator and listIterator(int) listIterator methods are fail-fast
  7. The Enumeration Enumerations returned by elements() elements method are not fail-fast.
  8. Java Vector is synchronized legacy class.
  9. Java Vector available from JDK 1.0.

Java Vector constructors

Vector defined these protected data members:

  1. protected int capacityIncrement : The amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity. If the capacity increment is less than or equal to zero, the capacity of the vector is doubled each time it needs to grow.
  2. protected int elementCount : The number of valid components in this VectorVector object.
  3. protected Object[] elementData : The array buffer into which the components of the vector are stored.

Java Vector have four constructors.

Constructor Description
public Vector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.
public Vector(int initialCapacity) Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
public Vector(int initialCapacity, int capacityIncrement) Constructs an empty vector with the specified initial capacity and capacity increment.
public Vector(Collection<? extends E> c) Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Below code snippet show example to create Vector instances using it's constructors.

    /*Constructs an empty vector with size 10. It means vector will re-size when 11th
        element elements needs to be inserted into the Vector. Note: By default vector doubles its size. i.e.
        In this case the Vector size would remain 10 till 10 insertions and once we try to insert the 11th element
        It would become 20 (double of default capacity 10).*/

    Vector<Integer> vector1 = new Vector<>();

    // Constructs an empty vector with the specified initial capacity and standard capacity increment equal to zero.
    Vector<Integer> vector2 = new Vector<>(16);

    /*Construct an empty vector with the specified initial capacity and the amount by which the capacity is increased when the vector overflows.
        The initial capacity is 16 and capacityIncrement is 8. It means upon insertion of 17th element the size would be 24 (16+8) and on 25th insertion it would be 32(24+8). */

    Vector<Integer> vector3 = new Vector<>(16, 8);

    List<Integer> list = new ArrayList<>();
    // Constructs a vector containing the elements of the specified collection.
    Vector<Integer> vector4 = new Vector<>(list);
    

Java Vector methods

Method Description
public void addElement(E element) The object specified by element is added to the vector.
public int capacity() Returns the capacity of the vector.
public Object clone() Returns a duplicate of the invoking vector.
public boolean contains(Object element) Returns true if element is contained by the vector, and returns false if it is not.
public void copyInto(Object[] array) The elements contained in the invoking vector are copied into the array specified by array.
public E elementAt(int index) Returns the element at the location specified by index.
public Enumeration<E> elements() Returns an enumeration of the elements in the vector.
public void ensureCapacity(int size) Sets the minimum capacity of the vector to size.
public E firstElement() Returns the first element in the vector.
public int indexOf(Object element) Returns the index of the first occurrence of element. If the object is not in the vector, –1 is returned.
public int indexOf(Object element, int start) Returns the index of the first occurrence of element at or after start. If the object is not in that portion of the vector, –1 is returned.
public void insertElementAt(E element, int index) Adds element to the vector at the location specified by index.
public boolean isEmpty() Returns true if the vector is empty, and returns false if it contains one or more elements.
public E lastElement() Returns the last element in the vector.
public int lastIndexOf(Object element) Returns the index of the last occurrence of element. If the object is not in the vector, –1 is returned.
public int lastIndexOf(Object element, int start) Returns the index of the last occurrence of element before start. If the object is not in that portion of the vector, –1 is returned.
public void removeAllElements() Empties the vector. After this method executes, the size of the vector is zero.
public boolean removeElement(Object element) Removes element from the vector. If more than one instance of the specified object exists in the vector, then it is the first one that is removed. Returns true if successful and false if the object is not found.
public void removeElementAt(int index) Removes the element at the location specified by index.
public void setElementAt(E element, int index) Sets the component at the specified index of this vector to be the specified object.
public void setSize(int size) Sets the number of elements in the vector to size. If the new size is less than the old size, elements are lost. If the new size is larger than the old size, null elements are added.
public int size() Returns the number of elements currently in the vector.
public String toString() Returns the string equivalent of the vector.
public void trimToSize() Sets the vector’s capacity equal to the number of elements that it currently holds.

Example

Here is a simple program of Vector.

package com.walking.techie;

import java.util.Vector;

public class VectorDemo {

  public static void main(String[] args) {
    Vector<Integer> vector = new Vector<>(4, 6);

    vector.add(10);
    vector.add(20);
    vector.add(30);
    vector.add(40);
    vector.add(1);
    vector.addElement(45);
    System.out.println(vector);
    System.out.println("Vector size is : " + vector.size());
    System.out.println("Current capacity of the vector :" + vector.capacity());

    System.out.println("Is vector contain 40?: " + vector.contains(40));
    Integer[] integers = new Integer[6];
    vector.copyInto(integers);
    System.out.println("Elements of the vector copies into integers : ");
    for (Integer value : integers) {
      System.out.print(" " + value);
    }

    System.out.println("\nElement of vector at position 4 is : " + vector.elementAt(4));
    System.out.println("Latest element of the vector is : " + vector.lastElement());
  }
}

Output of above program is shown below:

[10, 20, 30, 40, 1, 45]
Vector size is : 6
Current capacity of the vector :10
Is vector contain 40?: true
Elements of the vector copies into integers :
 10 20 30 40 1 45
Element of vector at position 4 is : 1
Latest element of the vector is : 45

Iterate or Traverse over Vector

1. Iterating Vector in java using Java 8 forEach and lambda expression

package com.walking.techie;

import java.util.Vector;

public class VectorTraversal {

  public static void main(String[] args) {
    Vector<Integer> vector = new Vector<>(4, 6);

    vector.add(10);
    vector.add(20);
    vector.add(30);
    vector.add(40);
    vector.add(1);

    // using java 8 for each and lambda expression
    vector.forEach(e -> {
      System.out.print(e + " ");
    });
  }
}

Output of above program is shown below:

10 20 30 40 1 

2. Iterating Vector in java using Iterator

package com.walking.techie;

import java.util.Iterator;
import java.util.Vector;

public class VectorTraversal {

  public static void main(String[] args) {
    Vector<Integer> vector = new Vector<>(4, 6);

    vector.add(10);
    vector.add(20);
    vector.add(30);
    vector.add(40);
    vector.add(1);

    Iterator<Integer> iterator = vector.iterator();
    while (iterator.hasNext()) {
      System.out.print(iterator.next() + " ");
    }
  }
}

Output of above program is shown below:

10 20 30 40 1 

3. Iterating Vector in java using Enumeration

package com.walking.techie;

import java.util.Enumeration;
import java.util.Vector;

public class VectorTraversal {

  public static void main(String[] args) {
    Vector<Integer> vector = new Vector<>(4, 6);

    vector.add(10);
    vector.add(20);
    vector.add(30);
    vector.add(40);
    vector.add(1);

    Enumeration<Integer> enumeration = vector.elements();
    while (enumeration.hasMoreElements()) {
      System.out.print(enumeration.nextElement() + " ");
    }
  }
}

Output of above program is shown below:

10 20 30 40 1 

4. Iterating Vector in java using ListIterator

package com.walking.techie;

import java.util.ListIterator;
import java.util.Vector;

public class VectorTraversal {

  public static void main(String[] args) {
    Vector<String> vector = new Vector<>(4, 6);

    vector.add("Red");
    vector.add("Blue");
    vector.add("Green");
    vector.add("White");
    vector.add("Black");

    ListIterator<String> stringIterator = vector.listIterator();
    System.out.println("Forward direction traversal of vector");
    while (stringIterator.hasNext()) {
      System.out.print(stringIterator.next() + " ");
    }
    System.out.println();
    System.out.println("\nBackward direction traversal of vector");
    while (stringIterator.hasPrevious()) {
      System.out.print(stringIterator.previous() + " ");
    }

    stringIterator = vector.listIterator(vector.size());
    System.out.println();
    System.out.println("\nBackward direction traversal of vector");
    while (stringIterator.hasPrevious()) {
      System.out.print(stringIterator.previous() + " ");
    }

    System.out.println();
    System.out.println("\nForward direction traversal of vector");
    while (stringIterator.hasNext()) {
      System.out.print(stringIterator.next() + " ");
    }
  }
}

Output of above program is shown below:

Forward direction traversal of vector
Red Blue Green White Black

Backward direction traversal of vector
Black White Green Blue Red

Backward direction traversal of vector
Black White Green Blue Red

Forward direction traversal of vector
Red Blue Green White Black 

5. Iterating Vector in java using for each loop

package com.walking.techie;

import java.util.Vector;

public class VectorTraversal {

  public static void main(String[] args) {
    Vector<String> vector = new Vector<>(4, 6);

    vector.add("Red");
    vector.add("Blue");
    vector.add("Green");
    vector.add("White");
    vector.add("Black");

    // Iterate using the for each on vector
    System.out.println("Elements of vector");
    for (String string : vector) {
      System.out.print(string + " ");
    }
  }
}

Output of above program is shown below:

Elements of vector
Red Blue Green White Black 

1 comment :

  1. Very nice vector tutorial. you have explained it very well . There is also good java vector tutorial Click Here

    ReplyDelete