What is the Vector.clear method in Java?
The clear method of the Vector class can be used to remove all the elements present in the vector object.
A vector is a growable array of objects. Its elements are mapped to an index.
Syntax
public void clear()
This method doesn’t take any arguments and doesn’t return any values.
Code
The example below uses the clear method as follows:
import java.util.Vector;class VectorClearExample {public static void main( String args[] ) {// Creating VectorVector<Integer> vector = new Vector<>();// add elememtsvector.add(1);vector.add(2);vector.add(3);System.out.println("The Vector is: " + vector);vector.clear();// Print first elementSystem.out.println("After clearing the Vector is : " + vector);}}
Please click the
Runbutton on the code section above to see how theclearmethod works.
Explanation
In the code above,
- In line 5: We created a vector object.
Vector<Integer> vector = new Vector<>();
- In lines 8 to 10: We added three elements (
1,2,3) to the created vector object.
vector.add(1);
vector.add(2);
vector.add(3);
- In line 14: We removed the elements present in the vector object by using the
clearmethod.
vector.clear();
- After calling
clear, we printed the vector object.