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

最后修改: 2022年 8月 5日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

通过本教程,我们将了解如何在JavaArrayList中替换一个特定索引的元素。

2. Common Practice

2.常见的做法

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.

要替换一个现有的元素,首先,我们需要找到该元素在ArrayList中的确切位置。这个位置就是我们所说的索引。然后,我们可以用一个新的元素来替换旧的元素。

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.

ArrayList的索引是基于零的。因此,要替换第一个元素,0必须是作为参数传递的索引。

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

如果提供的索引超出了范围,将发生IndexOutOfBoundsException

3. Implementation

3.实施

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);

assertThat(aList).isEqualTo(EXPECTED);

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.

首先,我们创建一个有五个元素的ArrayList。然后,我们将第三个元素替换为7,将索引2替换为3。最后,我们可以看到,索引2的7被从列表中删除,并更新为新的值3。另外,请注意,列表的大小没有受到影响。

4. Conclusion

4.结论

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.

一如既往,本文的完整源代码可以在GitHub上找到