Java 25 (LTS) reference · 10 entries

Java List and ArrayList Methods

List and ArrayList methods: List.of(), add(), get(), set(), remove(), contains(), indexOf(), sort() and subList(), with the common traps explained and runnable examples.

ArrayList is the everyday mutable list; List.of() creates an immutable one. Indexes start at 0.

NameDescriptionSince
List.of() Create an immutable list from values. Adding or removing later throws UnsupportedOperationException. Java 9
list.add() Append an element to the end of a list, or insert it at an index, shifting later elements right. Java 1.0
list.get() Return the element at an index (0-based). Throws IndexOutOfBoundsException for an invalid index. Java 1.0
list.set() Replace the element at an index and return the old value. The list's size doesn't change. Java 1.0
list.remove() Remove an element by index or by value. With a List<Integer>, remove(1) removes index 1, not the value 1. Java 1.0
list.size() Return the number of elements in a list. isEmpty() is a clearer way to check for zero. Java 1.0
list.contains() Return true if the list holds an element equal to the given one (using equals()). O(n) for ArrayList. Java 1.0
list.indexOf() Return the index of the first element equal to the given one, or -1. lastIndexOf() searches from the end. Java 1.0
list.sort() Sort a list in place with a Comparator, or by natural order when you pass null. Collections.sort() does the same. Java 8
list.subList() Return a view of part of a list, from an index up to (not including) another. Changes to the view affect the original. Java 1.0

Was this page helpful?