Skip to content

Java Vector Replace Element at Specific Index Example

This example shows how to replace an element at a specific index of Vector in Java. This example also shows how to replace the element at a specific index of the vector using the set and setElementAt methods.

How to replace the element at a specific index of Vector in Java?

The Vector set method replaces an element at the specified index of this vector object.

The set method replaces an element at the specified position of the vector and returns the old element.

Output

We can also use the setElementAt method instead of the set method to replace an element.

This method is identical to the set method in functionality.

Output

Difference between the set and setElementAt methods

1. The order of the parameter of the setElementAt method is reversed. The set method has an index as the first parameter and the element as the second while the setElementAt method has the element as the first parameter and an index as the second.

2. The set method returns the old element that was replaced by the new element at the specified position, while the return type of the setElementAt method is void.

3. The setElementAt method was part of the original Vector class. The set method is introduced when the Vector class was rewritten to implement the List interface in Java 2 and conforms to a newer standard. Hence, it is suggested to use the set method to replace an element in the vector.

This example is a part of the Java Vector 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.