Java ArrayList replace at specific index
⚡TLDR
To replace an element at a specific index in an ArrayList
, use set(int index, E element)
:
Result: [A, New, C]
.
Pro tip: Avoiding index out of bounds
Programs hate surprises, like IndexOutOfBoundsException
. Always check if the index is valid:
Find it first, then replace
Don’t know the index? No problem! Find it with indexOf
, then replace it:
When conditions apply: conditional replacement
Need to replace only specific elements? Iterate and put condition in set
:
Advancing your skills: effective usage of set()
- Always access elements with
get()
prior to replacing them withset()
. set()
only trades places. The list size stays the same.- Working with custom objects? Make sure they override
equals
andhashCode
for accurateindexOf
operations.
Building your own stage: custom replace method
A custom replaceLightBulb
method can be a handy tool:
Linked
Linked
Was this article helpful?