Vector Programs in Java for Best Practice

In this tutorial, we have listed various types of Vector programs in Java for best practice based on Vector methods, Enumeration, Iterator, and ListIterator.

Before going to practice, it is recommended that you first read vector tutorial to clear basic concepts of Vector.

Java Vector Program based on Enumeration


Let’s create a program where we will iterate elements of vector list using Enumeration. We will also add or remove an element during the iteration. It will not throw ConcurrentModificatioException. Follow all the steps in the given source code.

Program 1:

package vectorTest; 
import java.util.Enumeration; 
import java.util.Vector; 
public class VectorEnumerationEx { 
public static void main(String[] args) 
{ 
// Create vector object of type String. 
   Vector<String> v = new Vector<String>(); 

// Adding elements to vector using add() method of vector class. 
    v.add("A"); // Adding element at index 0.
    v.add("B"); // Adding element at index 1.
    v.add("C"); // Adding element at index 2.
    v.add("D"); // Adding element at index 3.
    v.add("E"); // Adding element at index 4.

// Call elements() method to iterate vector. 
   Enumeration<String> en = v.elements(); // Return type is Enumeration. 
   System.out.println("Vector elements are: "); 

// Checking the next element availability using reference variable en in the while loop. 
   while(en.hasMoreElements())
   { 
// Moving cursor to the next element. 
    Object obj = en.nextElement(); // Return type is Object. 
    System.out.println(obj); 

// Adding and removing an element during iteration using Enumeration. 
// Enumeration is fail-safe in a vector. So, it will not throw any exception. 
    v.removeElementAt(4); 
    v.add(4, "G"); 
  } 
  System.out.println("Vector list after adding elements during Iteration"); 
  System.out.println(v); 
 } 
}
Output: 
       Vector elements are: A B C D G 
       Vector list after adding elements during Iteration 
       [A, B, C, D, G]

Vector Program based on Iterator


Let’s create a program where we will iterate elements of vector in forwarding direction using Java Iterator. When we add or remove an element during the iteration, it will throw ConcurrentModificationException. Look at the source code.


Program 2: 

package vectorTest; 
import java.util.Iterator; 
import java.util.Vector; 
public class VectorIteratorExample { 
public static void main(String[] args) 
{ 
   Vector<Integer> v = new Vector<Integer>(); 
   v.add(20); 
   v.add(30); 
   v.add(40); 
   v.add(50); 
   v.add(60); 

// Call iterator() method to iterate elements of vector. 
   Iterator<Integer> itr = v.iterator(); // Return type is Iterator. 
   System.out.println("Vector elements are: "); 

// Checking the next element availability in the list. 
   while(itr.hasNext())
   { 
  // Moving cursor to the next element. 
     Object obj = itr.next(); // Return type is Object. 
     System.out.println(obj); 

  // Adding and removing an element during iteration using iteration. It will throw ConcurrentModificationException. Since, Iterator is fail-fast in vector. 
     v.add(4, 70); 
   } 
   System.out.println("Vector list after adding elements during Iteration"); 
   System.out.println(v); 
 } 
}
Output: 
      Vector elements are: 20 
      Exception in thread "main" java.util.ConcurrentModificationException at java.util.Vector$Itr.checkForComodification(Vector.java:1210) at 
      java.util.Vector$Itr.next(Vector.java:1163) at vectorTest.VectorIteratorExample.main(VectorIteratorExample.java:29)

Vector ListIterator Program in Java


Let’s make a program where we will iterate elements of vector list in both forward and backward direction using ListIterator. Using ListIterator, we can iterate a vector in both forward as well as backward direction. Look at the below program code.


Program 3: 

package vectorTest; 
import java.util.ListIterator; 
import java.util.Vector; 
public class VectorListIteratorEx { 
public static void main(String[] args) 
{ 
  Vector<String> v = new Vector<String>(); 
  v.add("a"); 
  v.add("ab"); 
  v.add("abc"); 
  v.add("abcd"); 
  v.add("abcde"); 

// Call listIterator() method to iterate in the forward direction. 
   ListIterator<String> litr = v.listIterator(); 
   System.out.println("Traversing in Forward Direction "); 
   while(litr.hasNext())
   { 
      Object obj = litr.next(); // Return type is Object. 
      System.out.println(obj); 
   } 
// This statement will iterate from index position 3 in the backward direction.
   ListIterator<String> litr1 = v.listIterator(3);  
   System.out.println("Traversing in Backward Direction"); 
   while(litr1.hasPrevious())
   { 
      System.out.println(litr1.previous()); 
   } 
 } 
}
Output: 
       Traversing in Forward Direction 
       a ab   abc abcd abcde 
       Traversing in Backward Direction 
       abcd abc ab a

How to Sort Vector Elements in Java?


We know that vector maintains the insertion order that means it displays the same order in which they got added elements to the vector but we can also sort vector elements in the ascending order using Collections.sort() method. Let’s take an example program to sort vector elements of the collection object.

Program 4:

package vectorTest; 
import java.util.Collections; 
import java.util.Vector; 
public class SortingVectorEx { 
public static void main(String[] args) 
{ 
   Vector<String> v = new Vector<String>(); 
   v.add("Cricket"); 
   v.add("Football"); 
   v.add("Hockey"); 
   v.add("Volleyball"); 
   v.add("Basketball"); 

// By default vector maintains the insertion order.  
   System.out.println("Vector elements before sorting:"); 
   for(int i = 0; i < v.size(); i++)
   { 
  // Call get() method to fetch elements from index and pass the parameter i. 
     Object obj = v.get(i); // Return type of get() method is an Object. 
     System.out.println(obj); 
   }
// Now call Collections.sort() method to sort elements of vector in the ascending order. 
   Collections.sort(v); 

// Display vector elements after sorting. 
   System.out.println("Vector elements after sorting:"); 
   for(int i = 0; i < v.size(); i++)
   { 
      Object elements = v.get(i); 
      System.out.println(elements); 
   } 
  } 
}
Output: 
       Vector elements before sorting: 
       Cricket Football Hockey Volleyball Basketball 
       Vector elements after sorting: 
       Basketball Cricket Football Hockey Volleyball

How to get SubList of Vector Elements in Java?


We can get a sublist of vector elements using subList() method of vector class. This method will return a range of elements from the list between fromIndex, inclusive, and toIndex, exclusive.

The general syntax of subList() method is as follows:

public List subList(int fromIndex, int toIndex)

Let’s write a Java program where we will get the sublist of elements of vector list. Look at the program source code to understand better.

Program 5:

package vectorTest; 
import java.util.List; 
import java.util.Vector; 
public class SublistExample { 
public static void main(String[] args) 
{ 
  Vector<String> v = new Vector<String>(); 
  v.add("Element1"); 
  v.add("Element2"); 
  v.add("Element3"); 
  v.add("Element4"); 
  v.add("Element5"); 
  v.add("Element6"); 

// Call subList() method to get a range of elements from the list. 
   List<String> subList = v.subList(1, 5); 
   System.out.println("Sub list elements:"); 
  for(int i = 0 ; i < subList.size() ; i++)
  { 
  // Call get() method to fetch elements from index and pass the parameter i. 
     Object obj = subList.get(i); // Return type of get() method is an Object. 
     System.out.println(obj); 
  } 
// We can also remove a range of elements using subList() method like this: 
   System.out.println("List of elements after removing:"); 
   v.subList(3, 5).clear(); 
   System.out.println(v); 
  } 
}
Output: 
       Sub list elements: 
       Element2 Element3 Element4 Element5 
       List of elements after removing: 
       [Element1, Element2, Element3, Element6]

Convert Vector to List and ArrayList


We can convert a Vector into List using Collections.list(vector.elements()) method. This method will return a list of elements. Let’s see a simple example to understand concept.

Program 6: 

package vectorTest; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.List; 
import java.util.Vector; 

public class ConversionExample { 
public static void main(String[] args) 
{ 
   Vector<String> v = new Vector<String>(); 
   v.add("Element1"); 
   v.add("Element2"); 
   v.add("Element3"); 
   v.add("Element4"); 
   System.out.println("Vector Elements:"); 
   for (String str : v)
   { 
     System.out.println(str); 
   } 
// Converting Vector to List. 
   List<String> list = Collections.list(v.elements());
   System.out.println("List Elements:"); 
   for (String str2 : list)
   { 
     System.out.println(str2); 
   } 
// Converting Vector to ArrayList. 
   ArrayList<String> al = new ArrayList<String>(v); 
   System.out.println("ArrayList Elements :"); 
   for (String s : al)
   { 
     System.out.println(s); 
   } 
  } 
}
Output: 
       Vector Elements: 
       Element1 Element2 Element3 Element4 
       List Elements: Element1 Element2 Element3 Element4 
       ArrayList Elements : Element1 Element2 Element3 Element4

How to convert Vector to String array in Java?


Using toString() method of a Vector class, we can convert a Vector of Strings to an array. The syntax for toString() method is given below:

public String toString(); // It returns a string representation of each element of vector.

Let’s take an example program based on it.

Program 7:

package vectorTest; 
import java.util.Vector; 
public class VectorToArrayExample { 
public static void main(String[] args) 
{ 
  Vector<String> v = new Vector<String>(); 
  v.add("Element1"); 
  v.add("Element2"); 
  v.add("Element3"); 
  v.add("Element4"); 
  v.add("Element5"); 

// Call size() method to get the size of vector. 
   int size = v.size(); 
   System.out.println("Size of Vector: " +size); 

// Converting vector to Array. 
// Create an object of String array and pass the parameter size. 
   String[] str = new String[size]; 

// Call toArray() method to get an array representation of the elements of this vector. 
   String[] arrayOfElements = v.toArray(str); // It returns an array containing all the elements of this vector. 

// Displaying Array Elements. 
   System.out.println("String Array Elements:"); 
   for(int i = 0; i < arrayOfElements.length; i++)
   { 
      System.out.println(arrayOfElements[i]); 
   } 
  } 
}
Output: 
       Size of Vector: 5 
       String Array Elements: 
       Element1 Element2 Element3 Element4 Element5

In the above program source code, line number 20 and 22 can be also written in one step like this:

String[ ] arrayOfElements = v.toArray(new String[v.size()]);

Hope that this tutorial has covered all important Java vector example programs. I hope that you will have understood vector example programs and enjoy them.
Thanks for reading!!!