Skip to content

Java Vector Clear or Remove All Elements Example

This example shows how to clear or remove all elements from the Vector in Java. This example also shows how to clear or remove all Vector elements using clear, removeAllElements, and setSize methods.

How to clear or remove all elements from Vector in Java?

There are several ways using which we can remove all elements from the vector object as given below.

1. Using the clear method

The Vector clear method removes all elements from this vector object.

The vector object becomes empty after this method call.

Output

Please also visit how to check if the vector is empty example to know more.

2. Using the removeAllElements method

The Vector removeAllElements method is similar to the clear method and removes all elements from this vector object.

Output

3. Using the setSize method

The Vector setSize method sets the size of this vector object to the specified new size.

To clear or empty the vector object, we will pass 0 to this method as given below.

Output

Which method should I use?

Let’s have a look at the source code of all these Vector methods.

As we can see from the source code, the clear method simply calls the removeAllElements method. The removeAllElements method and setSize method iterates through the vector elements and sets them to null.

As far as performance is concerned, all three will more or less perform the same. Using the clear method is a preferred approach just because it conforms to the new JDK standard.

Please also visit how to remove elements from Vector in Java example to know more.

This example is a part of the Vector in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Vector Documentation

About the author

Leave a Reply

Your email address will not be published.