EN
Java - modify items in ArrayList
0 points
In this article, we would like to show you how to modify items in the ArrayList in Java.
Quick solution:
xxxxxxxxxx
1
myArrayList.set(index, element);
Where:
myArrayList
- ArrayList name,index
- index of the element to replace,element
- element to be stored at the specified position.
In this example, we modify items with the specified index (0
and 1
) using set()
method.
xxxxxxxxxx
1
import java.util.ArrayList;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<String> fruits = new ArrayList<>();
7
8
// add items to the ArrayList
9
fruits.add("Apple");
10
fruits.add("Banana");
11
fruits.add("Cherry");
12
13
// modify/change items
14
fruits.set(0, "Orange");
15
fruits.set(1, "Kiwi");
16
17
System.out.println(fruits);
18
}
19
}
Output:
xxxxxxxxxx
1
[Orange, Kiwi, Cherry]
References