The Vector
class is a growable array of objects. The elements of Vector
can be accessed using an integer index and the size of a Vector can be increased or decreased.
Read more about
Vector
here.
The setElementAt
method of the Vector
class can be used to replace the element present at the specific index of the vector object.
public void setElementAt(E obj,int index)
This method takes two arguments.
The element to be replaced in the vector
object.
The index at which the new element is to be replaced. The index should be positive and less than the size of the vector
object. Otherwise, ArrayIndexOutOfBoundsException
will be thrown.
index
>= 0 && index
< size()
This method doesn’t return any value.
import java.util.Vector;class SetElementAt {public static void main( String args[] ) {// Creating VectorVector<Integer> vector = new Vector<>();// add elememtsvector.add(10);vector.add(40);vector.add(30);System.out.println("The Vector is: " + vector); // [10,40,30]vector.setElementAt(20, 1); // [10,20,30]System.out.println("\nAfter calling setElementAt(20,1). The Vector is: " + vector);}}
In the code above:
In line 5: We created a vector object.
In lines 8 to 10: We added three elements, 10,40,30
, to the created vector object.
In line 14: We used the setElementAt
method of the vector
object to replace the element present at index 1
with the value 20
. Now, the vector will be 10,20,30
.