In this example, we will see how to remove all the elements from a Vector. We will be using clear() method of Vector class to do this.
public void clear()
: Removes all of the elements from this Vector. The Vector will be empty after this method call.
Example
Here we are displaying the size of the Vector before and after calling clear() method. The steps are as follows:
1) Create a Vector.
2) Add elements to it.
3) Call clear() method to remove all the elements.
import java.util.Vector; public class RemoveAll { public static void main(String[] args) { // Creating a Vector of Strings Vector<String> vector = new Vector<String>(); //Adding elements to the Vector vector.add("C++"); vector.add("Java"); vector.add("Cobol"); vector.add("C"); vector.add("Oracle"); System.out.println("Current size of Vector: "+vector.size()); // Calling clear() method of Vector API vector.clear(); System.out.println("Size of Vector after clear(): "+vector.size()); } }
Output:
Current size of Vector: 5 Size of Vector after clear(): 0
Leave a Reply