Java Reference ยท Collections
Java List.get() and set() methods
Reference for Java List.get() and set(): read and replace elements by index, return values, bounds errors, cost by implementation and Java 21 getFirst().
get(int index) returns the element at a position, and set(int index, E element) replaces it. Together they treat a list like an array: positions start at 0 and the last valid index is size() - 1. Neither method changes the size of the list.
set() returns the value that was previously stored, which is handy for swaps. Both methods throw IndexOutOfBoundsException for an index outside the range, and set() is also rejected by immutable lists.
String first = list.get(0); String old = list.set(0, "new");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
E get(int index) E set(int index, E element)
| Name | Description |
|---|---|
index |
Zero-based position; valid range 0 <= index < size(). |
element |
The new value. null is accepted by lists that allow null. |
Returns: get returns the element at the index; set returns the element that was replaced.
Throws: IndexOutOfBoundsException when the index is negative or >= size(); UnsupportedOperationException from set on an immutable list; ClassCastException, NullPointerException or IllegalArgumentException if the list refuses the element.
Usage notes
- Cost:
O(1)forArrayList;O(n)forLinkedList, so avoid index loops over linked lists. set()is not a structural change, so it does not triggerConcurrentModificationExceptionin a running for-each loop.- No auto-grow: unlike arrays in some languages,
set(size(), x)fails; useadd()to append. - Boxed values:
list.get(i) == list.get(j)compares references forIntegervalues outside -128..127; useequals(). - Swapping:
Collections.swap(list, i, j)does it in one call. - Java 21:
getFirst()andgetLast()throwNoSuchElementExceptionon an empty list (instead ofIndexOutOfBoundsExceptionfromget(0)). - Updating in place: for a transformation of every element prefer
replaceAll().