What is the Vector.setElementAt method in Java?

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.

Syntax

public void setElementAt(E obj,int index)

Argument

This method takes two arguments.

  1. The element to be replaced in the vector object.

  2. 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()

Return value

This method doesn’t return any value.

Code

import java.util.Vector;
class SetElementAt {
public static void main( String args[] ) {
// Creating Vector
Vector<Integer> vector = new Vector<>();
// add elememts
vector.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);
}
}

Explanation

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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources