Skip to content

Insert Element at the Beginning of Java Vector Example

This example shows how to insert the element at the beginning of the Vector in Java. This example also shows how to insert an element at any index in Vector using the add and insertElementAt methods.

How to insert an element at the beginning of the Vector in Java (at the front)?

The Vector add method inserts the specified element at the specified index in this vector object.

It inserts the element at the given index of the vector object. This method shifts the existing elements at and after the specified index to the right by adding 1 to their indices.

To insert the element at the beginning of the Vector object, we need to pass the index as 0 as given below.

Output

Important Note:

There are two versions of the add method in the Vector class, one is with the index parameter and another is without the index parameter. The add method without the index parameter always appends the elements at the end of the Vector object.

We can also use the Vector insertElementAt method instead of the above given add method to insert the element at the front of the vector object.

The insertElementAt method is identical to the add method in functionality and inserts the specified element at the given index of the vector object.

Output

Note: The sequence of parameters of the insertElementAt method is in the reverse order as compared to the add method. The add method has the index as the first parameter and the element as the second parameter, while the insertElementAt method has the element as the first parameter and the index as the second parameter.

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.