Java Utility Library

Java Vector - setElementAt() Method



The java.util.Vector.setElementAt() method is used to set the component at the specified index of the vector to be the specified object. The previous component at that position is discarded.

Syntax

public void setElementAt(E obj, int index)

Here, E is the type of element maintained by the container.


Parameters

obj Specify object to set with.
index Specify index number of the component to set.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if the index is out of range i.e., (index < 0 || index > size()).

Example:

In the example below, the java.util.Vector.setElementAt() method is used to set the element at the specified index of the vector to be the specified element.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVector = new Vector<Integer>();

    //populating vector
    MyVector.add(10);
    MyVector.add(20);
    MyVector.add(30);
    MyVector.add(40);
    MyVector.add(50);

    System.out.println("Before method call, MyVector contains: " + MyVector);
    MyVector.setElementAt(1000, 1);
    System.out.println("After method call, MyVector contains: " + MyVector);    
  }
}

The output of the above code will be:

Before method call, MyVector contains: [10, 20, 30, 40, 50]
After method call, MyVector contains: [10, 1000, 30, 40, 50]

❮ Java.util - Vector