Java Vector clear() Method Tutorial

In this section, we will learn what the Vector clear() method is and how to use it in Java.

What is Java Vector clear() Method?

The Java Vector clear() method is used to clear the entire elements of a vector object.

Basically, after calling this method on a vector object, its entire elements will be removed and its size will return to 0.

Note: when calling the clear() method, the size() method will return the value 0 if called, because this method relates to the current number of elements in a vector object. But the capacity of that vector object still is a number above 0. Hence, if you call the capacity() method, you’ll get a number other than 0.

Java Vector clear() Method Syntax:

public void clear()

clear() Method Parameters:

The method does not take an argument.

clear() Method Return Value:

The return value of this method is void.

clear() Method Exceptions:

The method does not throw an exception.

Example: using Vector clear() method

import java.util.Vector; 
public class Main {

    public static void main(String[] args){
        
        Vector <String> vector = new Vector<>();
        vector.add("Jack");
        vector.add("Omid");
        vector.add("Ellen");
        vector.add("John");

        System.out.println("The current size of the vector object: "+vector.size());
        vector.clear();
        System.out.println("The size of the vector object after calling the clear method: "+ vector.size());
        System.out.println("The current capacity of the vector object after calling the clear method: "+ vector.capacity());
    }
}

Output:

The current size of the vector object: 4

The size of the vector object after calling the clear method: 0

The current capacity of the vector object after calling the clear method: 10
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies