Java ArrayListset() Method
Example
Replace an item in a list:
import java.util.ArrayList;public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); cars.set(0, "Opel"); System.out.println(cars); } }Definition and Usage
Theset() method replaces an item at a specified position in the list and returns the item that was previously at that position.
Syntax
public T set(intindex, Titem)T refers to the data type of items in the list.
Parameter Values
| Parameter | Description |
|---|---|
| index | Required. The position of the item to be replaced. |
| item | Required. The new item to be placed at the specified position. |
Technical Details
| Returns: | The item which was previously at the specified position in the list. |
|---|---|
| Throws: | IndexOutOfBoundsException - If the index is less than zero, equal to the size of the list or greater than the size of the list. |
Related Pages
❮ ArrayList Methods

