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.
1 |
public E set(int index, E element) |
The set
method replaces an element at the specified position of the vector and returns the old element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Vector; public class VectorReplaceElement { public static void main(String[] args) { Vector<String> vColors = new Vector<String>(); vColors.add("Red"); vColors.add("Green"); vColors.add("Blue"); /* * To replace an element, use * the set method */ /* * this will replace an element at * index 1 i.e. "Green" with "Purple" and * return "Green" */ System.out.println( vColors.set(1, "Purple") ); System.out.println("Vector contains: " + vColors); } } |
Output
1 2 |
Green Vector contains: [Red, Purple, Blue] |
We can also use the setElementAt
method instead of the set
method to replace an element.
1 |
public void setElementAt(E element, int index) |
This method is identical to the set
method in functionality.
1 2 3 4 5 6 7 8 9 10 |
Vector<String> vColors = new Vector<String>(); vColors.add("Red"); vColors.add("Green"); vColors.add("Blue"); //we can also use the setElementAt method vColors.setElementAt("Purple", 1); System.out.println("Vector contains: " + vColors); |
Output
1 |
Vector contains: [Red, Purple, Blue] |
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