Explain Codes LogoExplain Codes Logo

Java ArrayList replace at specific index

java
index-out-of-bounds
list-manipulation
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 28, 2024
TLDR

To replace an element at a specific index in an ArrayList, use set(int index, E element):

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C")); list.set(1, "New"); // B is replaced by New at index 1. B, we’ll miss you!

Result: [A, New, C].

Pro tip: Avoiding index out of bounds

Programs hate surprises, like IndexOutOfBoundsException. Always check if the index is valid:

public void safeReplace(ArrayList<String> list, int index, String newElement) { // We're not the wild west. We check our guns ... eh values, I mean. if (index >= 0 && index < list.size()) { list.set(index, newElement); } else { throw new IndexOutOfBoundsException("Hold your horses! That index doesn't exist: " + index); } }

Find it first, then replace

Don’t know the index? No problem! Find it with indexOf, then replace it:

int indexToReplace = list.indexOf("Old"); if (indexToReplace != -1) { list.set(indexToReplace, "New"); // Old, you're getting a makeover! }

When conditions apply: conditional replacement

Need to replace only specific elements? Iterate and put condition in set:

for (int i = 0; i < list.size(); i++) { if ("Old".equals(list.get(i))) { // "Old", it’s not you, it’s me… list.set(i, "New"); } }

Advancing your skills: effective usage of set()

  • Always access elements with get() prior to replacing them with set().
  • set() only trades places. The list size stays the same.
  • Working with custom objects? Make sure they override equals and hashCode for accurate indexOf operations.

Building your own stage: custom replace method

A custom replaceLightBulb method can be a handy tool:

public <T> void replaceLightBulb(ArrayList<T> list, int index, T newElement) { // Someone's gotta check the boundaries if (index < 0 || index >= list.size()) { throw new IndexOutOfBoundsException("Nope! Can't replace a bulb that doesn't exist!"); } // Out with the old, in with the new! T oldElement = list.get(index); list.set(index, newElement); System.out.println("The old " + oldElement + " is out. Hello to " + newElement + " at index " + index); }