Replace Element at a Specific Index in a Java ArrayList – 替换Java ArrayList中特定索引的元素

最后修改: 2022年 8月 5日

1. Overview


Through this tutorial, we’ll take a look at how to replace an element at a specific index in a Java ArrayList.


2. Common Practice


To replace an existing element, First, we need to find the exact position of that element in the ArrayList. This position is what we call the index. Then, we can replace the old element with a new one.


The most common way to replace an element in Java ArrayList is to use the set (int index, Object element) method. The set() method takes two parameters: the index of the existing item and the new item.

在Java ArrayList中替换一个元素的最常见方法是使用set (int index, Object element)方法set()方法需要两个参数:现有项目的索引和新项目。

The index of an ArrayList is zero-based. Thus, to replace the first element, 0 must be the index passed as a parameter.


The IndexOutOfBoundsException will occur if the provided index is out of bounds.


3. Implementation


Let’s see through an example how to replace an element in Java ArrayList at a specific index.

让我们通过一个例子来看看如何在Java ArrayList中替换一个特定索引的元素。

List<Integer> EXPECTED = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

List<Integer> aList = new ArrayList<>(Arrays.asList(1, 2, 7, 4, 5));
aList.set(2, 3);


First, we create an ArrayList with five elements. Then, we replace the third element with the value 7, having index 2 with 3. Finally, we can see that index 2 with value 7 is removed from the list and updated with the new value 3. Also, note that the list size is not impacted.


4. Conclusion


In this quick article, we learned how to replace an element at a specific index in Java ArrayList. Furthermore, you can use this method with any other List type like LinkedList. Just make sure that the List you are using is not immutable.

在这篇快速文章中,我们学习了如何在Java ArrayList中替换一个特定索引的元素。此外,你可以在任何其他List类型中使用此方法,如LinkedList。只需确保你所使用的List不是不可变的。

As always, the complete source code for this article can be found over on GitHub.