Skip to content
Tutorials Center
My learning

Topics

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.

Java
String first = list.get(0);
String old = list.set(0, "new");

Try it

Java Reading and replacing elements

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.

Java Errors and read-only lists

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

Java
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) for ArrayList; O(n) for LinkedList, so avoid index loops over linked lists.
  • set() is not a structural change, so it does not trigger ConcurrentModificationException in a running for-each loop.
  • No auto-grow: unlike arrays in some languages, set(size(), x) fails; use add() to append.
  • Boxed values: list.get(i) == list.get(j) compares references for Integer values outside -128..127; use equals().
  • Swapping: Collections.swap(list, i, j) does it in one call.
  • Java 21: getFirst() and getLast() throw NoSuchElementException on an empty list (instead of IndexOutOfBoundsException from get(0)).
  • Updating in place: for a transformation of every element prefer replaceAll().