In this source code example, we will demonstrate the usage of the Vector clear() method in Java with an example.
Vector java.util.Vector.clear() Method
The java.util.Vector.clear() method is used to remove all the elements from a Vector. Using the clear() method only clears all the elements from the vector and does not delete the vector. In other words, we can say that the clear() method is used to only empty an existing vector.
java.util.Vector.clear() Method Example
The below program illustrates the working of java.util.Vector.clear() method:
import java.util.*;
public class VectorDemo {
public static void main(String args[])
{
// Creating an empty Vector
Vector programLangs = new Vector();
// Use add() method to add elements in the vector
programLangs.add("C");
programLangs.add("C++");
programLangs.add("Java");
programLangs.add("Python");
programLangs.add("Go");
// Output the present vector
System.out.println("The vector is: " + programLangs);
// Clearing the Vector using clear() method
programLangs.clear();
// Displaying the final vector after clearing;
System.out.println("The final Vector: " + programLangs);
}
}
Output:
The vector is: [C, C++, Java, Python, Go] The final Vector: []
Example 2: Vector with Integer Numbers
import java.util.*;
public class VectorDemo {
public static void main(String args[])
{
// Creating an empty Vector
Vector primeNo = new Vector();
// Use add() method to add elements into the Queue
primeNo.add(2);
primeNo.add(3);
primeNo.add(5);
primeNo.add(7);
primeNo.add(11);
// Displaying the Vector
System.out.println("Vector: " + primeNo);
// Clearing the Vector using clear() method
primeNo.clear();
// Displaying the final vector after clearing;
System.out.println("The final Vector: " + primeNo);
}
}
Output:
Vector: [2, 3, 5, 7, 11] The final Vector: []