Wednesday, June 10, 2026
HomeLanguagesJavaVector clear() Method in Java

Vector clear() Method in Java

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. Below programs illustrate the Java.util.Vector.clear() method. Example 1: 

Java




// Java code to illustrate clear()
import java.util.*;
 
public class GFG {
    public static void main(String args[])
    {
        // Creating an empty Vector
        Vector<String> vt = new Vector<String>();
 
        // Use add() method to add elements into the Vector
        vt.add("Welcome");
        vt.add("To");
        vt.add("Geeks");
        vt.add("4");
        vt.add("Geeks");
 
        // Displaying the Vector
        System.out.println("Vector: " + vt);
 
        // Clearing the Vector using clear() method
        vt.clear();
 
        // Displaying the final vector after clearing;
        System.out.println("The final Vector: " + vt);
    }
}


Output:

Vector: [Welcome, To, Geeks, 4, Geeks]
The final Vector: []

Example 2: 

Java




// Java code to illustrate clear()
import java.util.*;
 
public class GFG {
    public static void main(String args[])
    {
        // Creating an empty Vector
        Vector<Integer> vt = new Vector<Integer>();
 
        // Use add() method to add elements into the Queue
        vt.add(10);
        vt.add(15);
        vt.add(30);
        vt.add(20);
        vt.add(5);
 
        // Displaying the Vector
        System.out.println("Vector: " + vt);
 
        // Clearing the Vector using clear() method
        vt.clear();
 
        // Displaying the final vector after clearing;
        System.out.println("The final Vector: " + vt);
    }
}


Output:

Vector: [10, 15, 30, 20, 5]
The final Vector: []

Time complexity: O(n). // n is the size of the vector.

Auxiliary Space: O(n).

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6896 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS