Skip to content

How to Add Elements to Vector in Java Example

This example shows how to add elements to Vector in Java. This example also shows how to add or insert elements to Vector using the add, addElement, and addAll methods.

How to add elements to Vector in Java?

How to add an element to a Vector object using the add and addElement methods?

The Vector add method adds the specified element to this vector object at the end.

The add method always returns true as specified by the add method of the Collection interface.

Output

The Vector addElement method is identical to the add method in functionality.

It appends the specified element at the end of the vector object. However, there is a difference in the return types of add and addElement methods. The add method returns a boolean value while the return type of the addElement method is void.

How to insert elements in the Vector at the specified index?

The overloaded add method accepts an index parameter.

It inserts the specified element at the specified index in the vector object. It shifts the subsequent elements to the right by adding 1 to their indices.

Output

The insertElementAt method is similar to this overloaded add method in functionality and inserts an element at the specified index of the vector object.

However, there is a difference in the order of the parameters.

How to add all elements of another collection to the Vector using the addAll method?

The Vector addAll method adds all elements of the specified collection object to this vector object.

It returns true if this vector is changed due to this method call.

The below given example shows how to add all elements of an ArrayList to a Vector object using the addAll method.

Output

The collection elements are appended at the end of this vector object.

If you want to insert the collection elements at the specific index instead of at the end, you can use the overloaded addAll method that also accepts an index.

Output

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.