Java Utility Library

Java ArrayList - set() Method



The java.util.ArrayList.set() method is used to replaces the element at the specified index in the ArrayList with the specified element.

Syntax

public E set(int index, E element)

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


Parameters

index Specify index number of the element to replace.
element Specify element to replace with.

Return Value

Returns the element at specified index of the ArrayList.

Exception

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

Example:

In the example below, the java.util.ArrayList.set() method is used to replace the element at the specified index in the ArrayList with the specified element.

import java.util.*;

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

    //populating ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);
    MyList.add(50);

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

The output of the above code will be:

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

❮ Java.util - ArrayList