Explain Codes LogoExplain Codes Logo

How to replace existing value of ArrayList element in Java

java
concurrent-modification
indexoutofboundsexception
listiterator
Nikita BarsukovbyNikita Barsukov·Feb 20, 2025
TLDR

Quick update of an ArrayList element is possible through the set method: specify the index and the new value.

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C")); list.set(1, "New"); // "B" gets a makeover to become "New" at index 1

The set method directly impacts the element at the mentioned index.

Safeguarding index: Confirm before replace

Before using the set method, ensure the indexed element exists to ward off IndexOutOfBoundsException. Use list.contains(value) to validate element presence, and list.indexOf(value) to determine position.

if (list.contains("B")) { list.set(list.indexOf("B"), "New"); // Stay safe during replacement }

This method protects against improper indexing while replacing values.

The Iterator method: Updating within iteration

Iterating over an ArrayList? Make use of ListIterator and its own set method for concurrent modification safety.

ListIterator<String> iterator = list.listIterator(); while (iterator.hasNext()) { if ("B".equals(iterator.next())) { iterator.set("New"); // The magical hat swaps "B" with "New" on the go } }

This replaces elements while looping to avoid concurrent modification issues.

Set vs Add: Don't get confused

Though seemingly simple, using the set method improperly can lead to errors. Steer clear of confusing it with add(index, element). While set changes elements directly, add shifts them, altering list size and causing potential chaos.

// Correct way list.set(2, "New"); // Here "New" firmly boots out the previous resident at index 2 // Incorrect way list.add(2, "New"); // Here, "New" shyly squeezes itself in at index 2, pushing others along

Exploration zone: Advanced tips and tricks

Condition-based updates

To update element based on a condition, interactively use the set method within a loop.

for (int i = 0; i < list.size(); i++) { String item = list.get(i); if (item.startsWith("A")) { list.set(i, "Updated"); // The "A" gang gets updated title tags } }

Custom objects: An extra layer

Dealing with custom objects? Just override the equals method, and contains and indexOf will work as per your requirements.

class Fruit { String name; // Constructor, getters, setters, equals, and hashCode methods } Fruit apple = new Fruit("apple"); // Ensure the `equals` method is overridden to check for name equality if (list.contains(apple)) { list.set(list.indexOf(apple), new Fruit("orange")); // Oops! Apple goes undercover as orange }

Thread-safe updates

Working in a multi-threaded environment? Think CopyOnWriteArrayList or synchronization methods to ensure thread safety.

Error handling: Fencing off exceptions

Beware of potentially explosive operations like trying to update at a non-existent index. Wrap them in try-catch blocks to diffuse IndexOutOfBoundsException.

try { list.set(10, "New"); // Trying a David Copperfield move at index 10 } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); // Handle the ex or release it into the wild }

The try-catch strategy not only prevents your app from stumbling but also helps you dance along with the errors.