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.


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.


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.


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.

Java 8 Vector Documentation

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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