Vector clear() method in Java

In this post, we are going to look at the clear() method of the Vector class in detail.

  • Method declaration – public void clear()
  • What does it do? – It will remove all of the elements present in the Vector at that time and thus will empty the vector
  • What does it return? – This method’s return type is void and thus will not return anything back to the calling function

Do you know? that clear() method internally uses the removeAllElements() method to remove the elements. Below is the internal implementation of the clear() method.

    public void clear() {
        removeAllElements();
    }
Example
public class Codekru {

	public static void main(String[] args) {

		Vector<String> v = new Vector<String>();

		v.add("hello");
		v.add("codekru");

		System.out.println("Vector: " + v.toString()); // printing the vector

		v.clear(); // clearing all of the vector's elements

		System.out.println("Vector: " + v.toString()); // printing the vector again

	}
}

Output –

Vector: [hello, codekru]
Vector: []
What if we try to use the clear() method on a null Vector?

It will throw a NullPointerException as illustrated in the below program.

public class Codekru {

	public static void main(String[] args) {

		Vector<String> v = new Vector<String>();

		v = null;

		System.out.println("Vector: " + v.toString()); // printing the vector

		v.clear(); // clearing all of the vector's elements

		System.out.println("Vector: " + v.toString()); // printing the vector again

	}
}

Output –

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Vector.toString()" because "v" is null
What if we try to use the clear() method on a Vector containing null objects?

In this case, the null objects will be added to the vector and will be cleared after using the clear() method on the vector.

public class Codekru {

	public static void main(String[] args) {

		Vector<String> v = new Vector<String>();

		v.add(null);
		v.add(null);
		
		System.out.println("Vector: " + v.toString()); // printing the vector

		v.clear(); // clearing all of the vector's elements

		System.out.println("Vector: " + v.toString()); // printing the vector again

	}
}

Output –

Vector: [null, null]
Vector: []

Please visit this link if you want to know more about the Vector class in java and its other functions or methods.

Hope you have liked the article. If you have any doubts or concerns, please feel free to write us in comments or mail us at [email protected].

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *