Java Vector class with examples

0
2191

In this article we are going see what is Java Vector, why do we use Vector in java and its commonly used methods with simple examples.

1. What is Vector in Java?

The Vector is a collections class that implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index

Vector is a legacy collections class in java.util package.Vector class is used to hold a group of elements and it is one of the  implementation class for List interface.

1.1. Vector features :

  1. The underlying data structure is resizable array (or) growable array.
  2. Duplicate objects are allowed.
  3. Insertion order is preserved ( means ordered).
  4. Heterogeneous objects are allowed (non generic version).
  5. Null insertion is possible.
  6. Implements Serializable, Cloneable and RandomAccess interfaces.
  7. Every method present in Vector is synchronized and hence Vector is Thread safe.

1.2. Why do we use Vector?

ArrayList has the similar features but not synchronized it’s operations. All Vector operations are synchronized, so whenever thread safety required to hold collection of elements and elements insertion order is required, Vector is good choice over ArrayListArrayList is faster if since it is non-synchronized. If we don’t have any explicit requirements for using either of them, we use ArrayList over Vector.

2. Create a Vector instance

Vector class provides following constructors to create a Vector instance.

//Constructs an empty vector so that its internal data array has size 10.
//incremental capacity zero
Vector v = new Vector();

//Constructs an empty vector with the specified initial capacity
//incremental capacity zero
Vector v = new Vector(int initialCapacity);

//Constructs an empty vector with the specified initial capacity and capacity increment.
Vector v = new Vector(int initialCapacity, int incrementalCapacity);

//Can be used to convert other collection object to Vector
Vector v = new Vector(Collection c);

3. Adding elements to Vector

public class JavaVectorAddElementsDemo {

	public static void main(String[] args) {
		
		Vector<String> v = new Vector<>();
		
		// adding single element
		v.add("Peter");//Collection interface method
		
		v.addElement("Martin");//Vector Specific method
		
		v.add(2, "Mike");//List specific method
		
		System.out.println(v); 
	}
}

Output :

[Peter, Martin, Mike]

4. Retrieve or Get elements from Vector

public class JavaVectorGetElementsDemo {

	public static void main(String[] args) {
		
		Vector<String> v = new Vector<>();
		
		v.addElement("Peter");
		v.addElement("Martin");
		v.addElement("Mike");
		
		System.out.println(v.firstElement());//Peter
		System.out.println(v.lastElement());//Mike
		System.out.println(v.get(1));//Martin
		System.out.println(v.elementAt(1));//Martin
	}
}

Output :

Peter
Mike
Martin
Martin

5. Update elements in Vector

public class JavaVectorUpdateElementsDemo {

	public static void main(String[] args) {
		
		Vector<String> v = new Vector<>();
		
		v.addElement("Peter");
		v.addElement("Martin");
		v.addElement("Mike");
		
		System.out.println(v.set(2, "Ashja"));//Mike - returns old
		v.setElementAt("Anand", 1);
		System.out.println(v);//[Peter, Anand, Ashja]
	}
}

Output :

Mike
[Peter, Anand, Ashja]

6. Remove elements from Vector

public class JavaVectorRemoveElementsDemo {

	public static void main(String[] args) {
		
		Vector<String> v = new Vector<>();
		
		v.addElement("Peter");
		v.addElement("Martin");
		v.addElement("Mike");
		v.addElement("Anand");
		v.addElement("Ashja");
		v.addElement("John");
		
		v.removeElement("John");
		System.out.println(v);//[Peter, Martin, Mike, Anand, Ashja]
		
		v.removeElementAt(2);
		System.out.println(v);//[Peter, Martin, Anand, Ashja]
		
		v.remove("Martin");
		System.out.println(v);//[Peter, Anand, Ashja]
		
		v.removeIf(name -> name.contains("A"));
		System.out.println(v);//[Peter]
		
		v.removeAllElements();
		System.out.println(v);//[]
	}
}

Output :

[Peter, Martin, Mike, Anand, Ashja]
[Peter, Martin, Anand, Ashja]
[Peter, Anand, Ashja]
[Peter]
[]

7. Iterate Vector elements

There are several ways to iterate Java Vector, in this example demonstrating how we iterate Vector using Enumeration  with elemetnts() of Vector class.

public class JavaVectorIterateElementsDemo {

	public static void main(String[] args) {
		
		Vector<String> v = new Vector<>();
		v.addElement("Peter");
		v.addElement("Martin");
		v.addElement("Mike");
		v.addElement("Anand");
		v.addElement("Ashja");
		v.addElement("John");
		
		System.out.println("---- Iterate using Enumeration ----");
		Enumeration<String> enumeration = v.elements();
		while (enumeration.hasMoreElements())
			System.out.println(enumeration.nextElement());
		
		System.out.println("---- Iterate using Stream.forEach() ----");
		v.stream().forEach(name -> System.out.println(name));
		
		System.out.println("---- Iterate using enhanced for-each loop ----");
	    for(String name : v)
	    	System.out.println(name);
	    
	    System.out.println("---- Iterate using java 8 forEach() ----");
	    v.forEach(name -> System.out.println(name));
	}
}

Output :

---- Iterate using Enumeration ----
Peter
Martin
Mike
Anand
Ashja
John
---- Iterate using Stream.forEach() ----
Peter
Martin
Mike
Anand
Ashja
John
---- Iterate using Stream.forEach() ----
Peter
Martin
Mike
Anand
Ashja
John
---- Iterate using java 8 forEach() ----
Peter
Martin
Mike
Anand
Ashja
John

8. Filter Vector elements

Since java 8, we can apply Stream operations to collections implementation classes.

public class JavaVectorFilterElementsDemo {

	public static void main(String[] args) {
		
		Vector<String> v = new Vector<>();
		
		v.addElement("Peter");
		v.addElement("Martin");
		v.addElement("Mike");
		v.addElement("Anand");
		v.addElement("Ashja");
		v.addElement("John");
		
		v.stream().filter(name -> name.startsWith("A"))
		          .forEach(name -> System.out.println(name));	
	}
}

Output :

Anand
Ashja

Conclusion :

In this article we have covered what is Vector class in Java, when do we use it, the key features of Vector class, creating and iterating a vector and its other common methods with the examples.

References

Vector documentation

LEAVE A REPLY

Please enter your comment!
Please enter your name here