Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.size()

Returns the number of elements in a list.

Available since: Java 1.2

Syntax

int size()

Return value

intThe number of elements in the list.

Examples

The size changes as elements are added:

void main() {
    List<String> list = new ArrayList<>();
    IO.println(list.size());
    list.add("x");
    list.add("y");
    IO.println(list.size());
}

Output:

0
2

Notes

Arrays have the length field, strings have the length() method, and all collections have the size() method. The last index of a list is size() - 1.

See also

  • List.isEmpty() — Checks whether a list is empty.
  • List.get() — Returns the list element at an index.
  • ArrayList — A resizable list backed by an array — the most common `List` implementation.

In the tutorial

  • Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.

Thanks for reading!

Donate to the site — we work hard for you.