Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collection.size(): count the elements in a collection

`Collection.size()` returns an element count as an `int`. The expression `repo.all().size()` counts the elements in the collection returned by `all()`.

Version: Java SE 21

Syntax

int size();
int count = collection.size();

Collection.size is a no-argument instance method of the java.util.Collection interface in Java SE 21. Calling collection.size() gives the element count as an int: 0 for an empty collection and Integer.MAX_VALUE if the count is greater than Integer.MAX_VALUE. If you only need to check whether the collection is empty, use collection.isEmpty().

The method reports the number of elements, not the internal capacity or the number of distinct values. In a list, each occurrence of a repeated value counts separately. A stored null also counts as an element if the collection allows it. ArrayList.size() runs in constant time, but Collection does not promise that for every implementation.

In repo.all().size(), Java calls all() first and then calls size() on the returned collection. The count covers only that collection, not necessarily everything in the repository. If all() returns null instead of a collection, the size() call throws NullPointerException. A saved int does not update when the collection changes: call size() again to get the new size.

Examples

import java.util.ArrayList;
import java.util.Collection;

public class Main {
    static final class Repository {
        private final Collection<String> items = new ArrayList<>(10);

        void add(String item) {
            items.add(item);
        }

        Collection<String> all() {
            return items;
        }
    }

    public static void main(String[] args) {
        Repository repo = new Repository();
        System.out.println(repo.all().size());

        repo.add("A");
        repo.add("A");
        int count = repo.all().size();
        System.out.println(count);

        repo.add("B");
        System.out.println(count);
        System.out.println(repo.all().size());
    }
}

Result

0
2
2
3

An initial capacity of `10` does not mean the list contains any elements: the first result is `0`. Two occurrences of `"A"` give `2`. After adding `"B"`, the saved `count` is still `2`, but a fresh call to `size()` returns `3`.

Related lessons

  • Java · Lesson 32 · Intermediate · Version: 2

Sources