Java Language In-place replacement of a List element


Example

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:

  • 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:

  1. The set operation will not cause a ConcurrentModificationException.
  2. The set operation is fast ( O(1) ) for ArrayList but slow ( O(N) ) for a LinkedList.
  3. An indexOf search on an ArrayList or LinkedList is slow ( O(N) ).