This example is about replacing a List
element while ensuring that the replacement element is at the same position as the element that is replaced.
This can be done using these methods:
Consider an ArrayList
containing the elements "Program starting!", "Hello world!" and "Goodbye world!"
List<String> strings = new ArrayList<String>();
strings.add("Program starting!");
strings.add("Hello world!");
strings.add("Goodbye world!");
If we know the index of the element we want to replace, we can simply use set
as follows:
strings.set(1, "Hi world");
If we don't know the index, we can search for it first. For example:
int pos = strings.indexOf("Goodbye world!");
if (pos >= 0) {
strings.set(pos, "Goodbye cruel world!");
}
Notes:
set
operation will not cause a ConcurrentModificationException
.set
operation is fast ( O(1)
) for ArrayList
but slow ( O(N)
) for a LinkedList
.indexOf
search on an ArrayList
or LinkedList
is slow ( O(N)
).