In-place replacement of a List element
suggest changeThis 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:
- set(int index, T type)
- int indexOf(T type)
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:
- The
setoperation will not cause aConcurrentModificationException. - The
setoperation is fast (O(1)) forArrayListbut slow (O(N)) for aLinkedList. - An
indexOfsearch on anArrayListorLinkedListis slow (O(N)).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents