Vector in Java with Example

vector example in java constructor and methods of vector

In this post, we will see the Vector in Java with Example.

Basic Points about Vector.

  • Vector is a legacy class which introduced in JDK1.0 which implements List, RandomAccess, Cloneable and Serializable interface.
  • It can store different types of element and maintain insertion order.
  • Vector uses indexing representation to store the elements, so we can vector elements randomly.
  • A vector allows duplicate elements.
  • We can have null as an element in Vector.
  • All of the methods of Vector are synchronized.
  • Vector objects are eligible for serialization and Cloning.
  •  Vector elements can be iterated through Iterator, Listiterator, and Enumeration.
  • Stack is the direct Known subclass of Vector.

Example which demonstrates Vector is slower than ArrayList.

package rrrr;
import java.util.*;
public class ArrayListVsVectorPerf {
public static void main(String[] args) {
	
	// define ArrayList Object
	List<String> listOfArrayList = new ArrayList<>();
	//get current time in milliseconds
	long l1 = System.currentTimeMillis();
	for(int i=0; i<1000000; i++) {
		//add ram 1M times
		listOfArrayList.add("ram");
	}
	//get current time in milliseconds
	long l2 = System.currentTimeMillis();	
	//l2 - l1 will return time took to add 1M times ram in listOfArrayList
	System.out.println("time taken by ArrayList "+(l2-l1));
	
	long l3 = System.currentTimeMillis();
	List<String> listOfVector = new Vector<>();
	for(int i=0; i<1000000; i++) {
		listOfVector.add("ram");
	}		
	long l4 = System.currentTimeMillis();	
	//l2 - l1 will return time took to add 1M times ram in listOfVector
	System.out.println("time taken by Vector    "+(l4-l3));	
}
}

Constructors of Vector in Java with Example.

Constructors – Vectors has four constructors.

Vector() – We are passing 10 as the initial capacity.

public Vector() {
    this(10);
}

Example using the default constructor.

import java.util.Vector;

public class VectorExample {
	public static void main(String[] args) {
		Vector<String> list = new Vector<>();
		list.add("ram");
		list.add("mohan");
		list.add("sohan");
		list.add("shyam");
		list.add("ram");

		System.out.println(list);
		System.out.println(list.capacity());
	}
}

Output is –

[ram, mohan, sohan, shyam, ram]
10

Vector(Collection  c) –  We can convert Vector to other types of collections using this constructor. Internal implementation of this constructor –

    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

Example 2 : –

import java.util.ArrayList;
import java.util.Vector;

public class VectorExample {
	public static void main(String[] args) {
		ArrayList<String> arraylist = new ArrayList<>();
		arraylist.add("ram");
		arraylist.add("mohan");
		arraylist.add("sohan");
		arraylist.add("shyam");
		arraylist.add("ram");
		System.out.println("As a arraylist ---- " + arraylist);
		System.out.println("Convert into Vector using Vector constructor");
		Vector<String> vectorObj = new Vector(arraylist);
		System.out.println("As a vector ----    " + vectorObj);
	}
}

Output is –

As a arraylist —- [ram, mohan, sohan, shyam, ram]
Convert into Vector using Vector constructor
As a vector —-      [ram, mohan, sohan, shyam, ram]


Vector(int initialCapacity) – We can create a Vector object with some different capacity instead of default capacity 10. The internal implementation of this constructor-

public Vector(int initialCapacity) {
    this(initialCapacity, 0);
}

Vector(int initialCapacity, int capacityIncrement) – We can create an empty vector with some different capacity also we can specify how new capacity will define. Internal implementation of this constructor –

public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}

Example 3 : –

import java.util.Vector;

public class VectorExample {
	public static void main(String[] args) {

		// We have define initial capacity 20
		Vector<String> list = new Vector<>(20);
		list.add("ram");
		list.add("mohan");
		list.add("sohan");
		list.add("shyam");
		list.add("ram");
		System.out.println(list);
		System.out.println(list.capacity());
	}
}

Output is –

[ram, mohan, sohan, shyam, ram]
20

Example 4 : –

import java.util.Vector;

public class VectorExample {
	public static void main(String[] args) {

		// We want to increase capacity 25
		Vector<String> list = new Vector<>(2, 25);

		list.add("ram");
		list.add("mohan");
		System.out.println(list);
		System.out.println("After adding two element capacity is--"
				+ list.capacity());
		list.add("sohan");
		list.add("shyam");
		list.add("ram");
		System.out.println(list);
		System.out.println("After adding more than two element capacity is--"
				+ list.capacity());

	}
}

Output is :-

[ram, mohan]
After adding two element capacity is–2
[ram, mohan, sohan, shyam, ram]
After adding more than two element capacity is–27

Different ways to iterate Vector in Java.

Iterate Vector using iterator.

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

public class VectorExample {
	public static void main(String[] args) {
		List<String> list = new Vector<>();
		list.add("ram");
		list.add("mohan");
		list.add("sohan");
		list.add("shyam");
		list.add("ram");

		Iterator<String> it = list.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output is –

ram
mohan
sohan
shyam
ram

Iterate Vector using Enumeration.


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

public class VectorExample {
	public static void main(String[] args) {
		Vector<String> list = new Vector<>();
		list.add("ram");
		list.add("mohan");
		list.add("sohan");
		list.add("shyam");
		list.add("ram");

		Enumeration<String> enm = list.elements();
		while (enm.hasMoreElements()) {
			System.out.println(enm.nextElement());
		}
	}
}

Output is –

ram
mohan
sohan
shyam
ram

Iterate Vector Using ListIterator.

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

public class VectorExample {
	public static void main(String[] args) {
		Vector<String> list = new Vector<>();
		list.add("ram");
		list.add("mohan");
		list.add("sohan");
		list.add("shyam");
		list.add("ram");

		ListIterator<String> listIte = list.listIterator();
		while (listIte.hasNext()) {
			System.out.println(listIte.next());
		}
	}
}

Output is –

ram
mohan
sohan
shyam
ram

Iterate Vector using a for-each loop.

import java.util.Vector;

public class VectorExample {
	public static void main(String[] args) {
		Vector<String> list = new Vector<>();
		list.add("ram");
		list.add("mohan");
		list.add("sohan");
		list.add("shyam");
		list.add("ram");

		for (String str : list) {
			System.out.println(str);
		}
	}
}

Output is –

ram
mohan
sohan
shyam
ram

Iterate Vector using for loop.

import java.util.Vector;

public class VectorExample {
	public static void main(String[] args) {
		Vector<String> list = new Vector<>();
		list.add("ram");
		list.add("mohan");
		list.add("sohan");
		list.add("shyam");
		list.add("ram");

		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
	}
}

Output is –

ram
mohan
sohan
shyam
ram

Vector methods with Example.

Vector add() method example

package com.netsurfingzone.vector;

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

public class VectorAddExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		Iterator<String> it = vector.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output:

john
will
steve

Vector add() method example – Adding elements to specific index.

package com.netsurfingzone.vector;

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

public class VectorAddIndexExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		// adding elements to specific index.
		vector.add(0,"john");
		vector.add(1,"will");
		vector.add(2,"steve");
		Iterator<String> it = vector.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output : –

john
will
steve

Vector addAll() method example

package com.netsurfingzone.vector;

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

public class VectorAddAllExample {
	public static void main(String[] args) {

		// create first vector object and add some elements
		Vector<String> vector1 = new Vector<String>();
		vector1.add("john");
		vector1.add("will");
		vector1.add("steve");

		// create second vector object and add some elements
		Vector<String> vector2 = new Vector<String>();
		vector2.add("moro");
		vector2.add("linto");
		vector2.add("van");

		// create third vector object and add some elements
		Vector<String> vector3 = new Vector<String>();
		vector3.add("ven");
		vector3.add("el");
		vector3.add("larco");

		// create fourth vector object and add previously created Vector's
		// object using addAll()
		Vector<String> vector = new Vector<String>();
		vector.addAll(vector1);
		vector.addAll(vector2);
		vector.addAll(vector3);

		Iterator<String> it = vector.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output:

john
will
steve
moro
linto
van
ven
el
larco

Vector addElement() method example

package com.netsurfingzone.vector;

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

public class VectorAddElementExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.addElement("jon");
		vector.addElement("will");
		vector.addElement("steve");
		Iterator<String> it = vector.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output:-

jon
will
steve

Vector capacity() method example

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorCapacityExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		System.out.println("Capacity before adding any elements---" + vector.capacity());
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		vector.add("john");
		vector.add("john");
		System.out.println("Capacity before adding elements---" + vector.capacity());
	}
}

Output:-


Capacity before adding any elements—10
Capacity before adding elements—20

Vector clear() method example

package com.netsurfingzone.vector;

import java.util.List;
import java.util.Vector;

public class VectorClearExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		System.out.println("Before clear() method---" + vector);
		vector.clear();
		System.out.println("After clear() method----" + vector);
	}
}

Before clear() method—[john, will, steve]
After clear() method—-[]

Vector firstElement() method example

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorFirstElementExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		System.out.println(vector.firstElement());
	}
}

Output –

john

Vector get() method example

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorGetExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		for (int i = 0; i < vector.size(); i++) {
			System.out.println(vector.get(i));
		}
	}
}

Vector indexOf() method example

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorIndexOfExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		System.out.println(vector.indexOf("will"));
	}
}

Output:- 1

Vector contains() method example.

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorContainsExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");

		// since vector object contains "will", below line will return true
		System.out.println(vector.contains("will"));

		// since vector object doesn't contains "smith", below line will return
		// false
		System.out.println(vector.contains("smith"));
	}
}

Output : –

true
false

Vector containsAll() method example

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorContainsAllExample {
	public static void main(String[] args) {
		Vector<String> vector1 = new Vector<String>();
		vector1.add("john");
		vector1.add("will");
		vector1.add("steve");

		Vector<String> vector2 = new Vector<String>();
		vector2.add("john");
		vector2.add("will");
		vector2.add("steve");

		// vector object containsAll() method will check vector1 contains all
		// elements in vector2 or not. For example since vector1 contains all
		// elements in vector2 contains same elements it will return true.
		System.out.println(vector1.containsAll(vector2));

		// create new Vector object vector3
		Vector<String> vector3 = new Vector<String>();
		vector3.add("john");
		vector3.add("will");

		// We have added two elements in vector3, which are present in vector1
		// so below line will again return true
		System.out.println(vector1.containsAll(vector3));

		// create new Vector object Vector4
		Vector<String> vector4 = new Vector<String>();
		vector4.add("smith");

		// since vector1 doesn't contains "smith", it will return false
		System.out.println(vector1.containsAll(vector4));
	}
}

Output:-

true
true
false

Vector copyInto() method example

The copyInto() method is used to copy vector elements to specific array.

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorCopyIntoExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		
		//Create a String array of size equal to vector
		String [] strArray = new String[vector.size()];
		
		//use Vector copyInto() method
		vector.copyInto(strArray);
		
		for(String s : strArray){
			System.out.println(s);
		}
	}
}

Output:-

john
will
steve

Vector elementAt() method example

This method returns the element to specified position. This method is similar to get() method in functionality.

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorElementAtExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");

		for (int i = 0; i < vector.size(); i++) {
			System.out.println(vector.elementAt(i));
		}
	}
}

Output:-

john
will
steve

Vector elements() method example

package com.netsurfingzone.vector;

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

public class VectorElementsExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");

		Enumeration<String> enumeration = vector.elements();
		while (enumeration.hasMoreElements()) {
			System.out.println(enumeration.nextElement());
		}
	}
}

Output is:-

john
will
steve

Vector ensureCapacity() method example

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorEnsureCapacityExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		System.out.println("capacity of vector is " + vector.capacity());		
		vector.ensureCapacity(40);
		System.out.println("capacity of vector is "+vector.capacity());

	}
}

capacity of vector is 10
capacity of vector is 40

Vector insertElementAt method Example

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorInsertElementAtExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		System.out.println(vector);

		// insert new element at 2nd position
		vector.insertElementAt("smith", 2);
		System.out.println(vector);
	}
}

Output:-

john, will, steve
john, will, smith, steve

Vector isEmpty() method example

This method used to check vector is empty or not.

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorIsEmptyExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		System.out.println("Before adding elements:-  " + vector.isEmpty());
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		System.out.println("After adding elements:-  " + vector.isEmpty());

	}
}

Output:-

Before adding elements:- true
After adding elements:- false

Vector iterator() method example

package com.netsurfingzone.vector;

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

public class VectorIteratorExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		Iterator<String> it = vector.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output:-

john
will
steve

Vector lastElement() method example.

This method returns the last element of Vector.

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorlastElementExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("john");
		vector.add("will");
		vector.add("steve");
		System.out.println(vector.lastElement());
	}
}

Output:-

steve

Vector remove() method example

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorRemoveExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("John");
		vector.add("Will");
		vector.add("Steve");
		vector.add("Sersi");
		vector.add("Sansa");
		System.out.println("Before removing the elements:-  " + vector);

		// remove(int index) example
		vector.remove(0);

		System.out.println("After removing the first element:-  " + vector);

		// remove(Object o) example
		vector.remove("Will");
		System.out.println("After removing the Will :-  " + vector);

		// removeAllElements() example
		vector.removeAllElements();
		System.out.println("After removing the all elements:-  " + vector);
	}
}

Output:-

Before removing the elements:- [John, Will, Steve, Sersi, Sansa]
After removing the first element:- [Will, Steve, Sersi, Sansa]
After removing the Will :- [Steve, Sersi, Sansa]
After removing the all elements:- []

Vector subList() method with Example.

package com.netsurfingzone.vector;

import java.util.Vector;

public class VectorSubListExample {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.add("John");
		vector.add("Will");
		vector.add("Steve");
		vector.add("Sersi");
		vector.add("Sansa");
		System.out.println("Before subList():- " + vector);
		System.out.println("After subList():- " + vector.subList(0, 2));

	}
}

Output:-

Before subList():- [John, Will, Steve, Sersi, Sansa]
After subList():- [John, Will]

That’s all about Vector in Java with Example.

You may like.

ArrayList in Java with Example.
LinkedList in Java with Example.
HashSet in Java with Example.
LinkedHashSet in Java with Example.
TreeSet in Java With Example.
HashMap in Java with Example.
Hashtable in Java with Example.
LinkedHashMap in Java with Example.
TreeMap in Java with Example.

See Vector docs.

Summary – We covered Vector in Java with Example. We covered Vector method and constructor with example.