To replace an element in Java Vector, set() method of java.util.Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element. The index of a Vector is zero-based. So, to replace the first element, 0 should be the index passed as parameter.
public Object set(int index, Object element)
The element which is at the specified index
IndexOutOfBoundsException when the index is out of range i.e, index < 0 or index >= size()
original vector : [1, 2, 3, 4, 5] after replace the value : [1, 2, 10, 4, 5] java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9
Time Complexity: O(n), where n is the length of the vector
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.