In-place replacement of a List element

suggest change

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:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Lists:
* Lists
* In-place replacement of a List element

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap