Scientech Easy Java Vector Example Programs | Scientech Easy

Monday, November 26, 2018

Java Vector Example Programs

In this tutorial, we will learn various example of Vector Programs in Java using Enumeration, Iterator, and ListIterator. We will also learn some important programs related to methods of the vector class. So, let's see example programs.

Java Vector Example Programs

Vector programs, Vector programs using Enumeration, Iterator, and ListIterator.

Vector Enumeration Example in Java 

In this example program, we will iterate elements of the vector using Enumeration. We will also add or remove an element during the iteration. It will not throw ConcurrentModificatioException.  We will explain all the steps in the program. 
Program source code 1: 
    package vectorTest; import java.util.Enumeration; import java.util.Vector; public class VectorEnumerationExample { public static void main(String[] args) { // Create a vector object with type String. Vector<String> v=new Vector<String>(); // Add elements to the vector using add() method of vector class. v.add("A"); v.add("B"); v.add("C"); v.add("D"); v.add("E"); // Call the element() 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 will not throw ConcurrentModificationException. // Enumeration is fail-safe in a vector. v.removeElementAt(4); v.add(4, "G"); } System.out.println("Vector elements after adding element during Iteration"); System.out.println(v); } }
    Output: Vector elements are: A B C D G Vector elements after adding element during Iteration [A, B, C, D, G]
Vector Iterator Example in Java 
In this example, We will iterate elements of the vector in forwarding direction using Iterator. When we add or remove an element during the iteration, it will throw ConcurrentModificationException. Let's see a simple program.
Program source code 2: 
    package vectorTest; import java.util.Iterator; import java.util.Vector; public class VectorIteratorExample { public static void main(String[] args) { // Create a vector object with type Integer. Vector<Integer> v=new Vector<Integer>(); // Add elements to the vector using add() method of vector class. v.add(20); v.add(30); v.add(40); v.add(50); v.add(60); // Call the iterator() method to iterate vector. Iterator<Integer> itr=v.iterator(); // Return type is Iterator. System.out.println("Vector elements are: "); // Checking the next element availability using reference variable itr in the while loop. 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 will throw ConcurrentModificationException. // Iterator is fail-fast in vector. v.add(4, 70); } System.out.println("Vector elements after adding element 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 Example in Java 
Using ListIterator, we can iterate a vector in both forward as well as backward direction. You follow all the above steps.
Program source code 3: 
    package vectorTest; import java.util.ListIterator; import java.util.Vector; public class VectorListIteratorExample { public static void main(String[] args) { // Create a vector object with type String. Vector<String> v=new Vector<String>(); v.add("a"); v.add("ab"); v.add("abc"); v.add("abcd"); v.add("abcde"); // Call the 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); } ListIterator<String> litr1=v.listIterator(3); // It will iterate from the index position 3 in the backward direction. 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 
You already know that vector maintains the insertion order that means it displays the same order in which they got added the elements to the vector but you can also sort the vector elements in the ascending order using Collections.sort() method. Let's see a simple example program to sort the vector elements.
Program source code 4:
    package vectorTest; import java.util.Collections; import java.util.Vector; public class SortingVectorExample { public static void main(String[] args) { // Create a vector object. Vector<String> v=new Vector<String>(); // Adding elements to a vector using reference variable v. 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 the Collections.sort() method to sort the elements of the vector in the ascending order. Collections.sort(v); // Display the 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.  
syntax:
public List subList(int fromIndex, int toIndex)
Program source code 5:
    package vectorTest; import java.util.List; import java.util.Vector; public class SublistExample { public static void main(String[] args) { // Create a vector object. Vector<String> v=new Vector<String>(); // Adding elements to a vector using reference variable v. 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 the List using Collections.list(vector.elements()) method. This method will return a list of elements. Let's see a simple example to understand the concept.
Program source code 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) { // Create a vector object. Vector<String> v=new Vector<String>(); // Adding elements to a vector using reference variable v. v.add("Element1"); v.add("Element2"); v.add("Element3"); v.add("Element4"); // Displaying Vector elements System.out.println("Vector Elements:"); for (String str : v){ System.out.println(str); } // Converting Vector to List. List<String> list = Collections.list(v.elements()); // Step 5: Displaying List 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); //Displaying ArrayList Elements. 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 of toString() method is given below:
Syntax:
public String toString(); // It returns a string representation of each element of a Vector.
Program source code 7:
    package vectorTest; import java.util.Vector; public class VectorToArrayExample { public static void main(String[] args) { // Create a vector object. Vector<String> v=new Vector<String>(); // Adding elements to a vector using reference variable v. 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 the vector to Array. // Create an object of String array and pass the parameter size. String[] str=new String[size]; // Line 1(say) // 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. // Line 2 // 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, The line number 1 and 2 can be also written in one step like this:
String[ ] arrayOfElements=v.toArray(new String[v.size()]); 
Final Words 
We hope that this article will help you to learn and practice example programs of the vector in Java. All programs are basic but important to make the command and clear the concepts of the vector in Java. 


Popular