Replacing Element in Java Vector
Last Updated :
11 Dec, 2020
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.
Declaration:
public Object set(int index, Object element)
Return Value:
The element which is at the specified index
Exception Throws:
IndexOutOfBoundsException
when the index is out of range
i.e, index < 0 or index >= size()
Implementation:
Java
import java.util.Vector;
public class Sias {
public static void main(String args[])
{
try {
Vector<Integer> vector = new Vector<>();
vector.add( 1 );
vector.add( 2 );
vector.add( 3 );
vector.add( 4 );
vector.add( 5 );
System.out.println( "original vector : "
+ vector);
vector.set( 2 , 10 );
System.out.println( "after replace the value : "
+ vector);
vector.set( 9 , 91 );
System.out.println( "after replace the value : "
+ vector);
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output
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
Share your thoughts in the comments
Please Login to comment...