Vector clear() Method in Java
Last Updated :
12 Dec, 2024
Improve
The Java.util.Vector.clear() method is used to remove all the elements from a Vector. Using the clear() method only clears all the element 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.
Syntax:
Vector.clear()
- Parameters: The method does not take any parameter
- Return Value: The function does not returns any value.
Example of Vector clear() Method
Below programs illustrate the Java.util.Vector.clear() method.
Example 1:
// Using Vector clear() Method
import java.util.*;
public class GFG
{
public static void main(String args[])
{
// creating an empty Vector
Vector<String> v = new Vector<String>();
// add elements in vector
v.add("Welcome");
v.add("To");
v.add("GFG");
// displaying the Vector
System.out.println("Elements in Vector : " + v);
// clearing the vector elements
v.clear();
// display vector after operation
System.out.println("Vector after Operation : " + v);
}
}
Output
Elements in Vector : [Welcome, To, GFG] Vector after Operation : []
Example 2:
// Using vector clear() Method
import java.util.*;
public class GFG
{
public static void main(String args[])
{
// creating an empty Vector
Vector<Integer> v = new Vector<Integer>();
// adding elements in vector
v.add(10);
v.add(15);
v.add(30);
// displaying the Vector
System.out.println("Vector: " + v);
// clearing vctor
v.clear();
// display vector after operation
System.out.println("The final Vector: " + v);
}
}
Output
Vector: [10, 15, 30] The final Vector: []