就地替换 List 元素
此示例是关于替换 List 元素,同时确保替换元素与替换元素位于相同位置。
这可以使用以下方法完成:
- set(int index,T type)
- int indexOf(T type)
考虑一个包含元素“程序开始!”,Hello World!的 ArrayList。和“再见世界!”
List<String> strings = new ArrayList<String>();
strings.add("Program starting!");
strings.add("Hello world!");
strings.add("Goodbye world!");
如果我们知道要替换的元素的索引,我们可以简单地使用 set,如下所示:
strings.set(1, "Hi world");
如果我们不知道索引,我们可以先搜索它。例如:
int pos = strings.indexOf("Goodbye world!");
if (pos >= 0) {
strings.set(pos, "Goodbye cruel world!");
}
笔记:
set操作不会导致ConcurrentModificationException。set的操作速度很快(O(1)),但是LinkedList的速度很慢(O(N))。- 在
ArrayList或LinkedList上搜索indexOf的速度很慢(O(N))。