Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

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

Use `Collection.size()` to read a collection’s element count as an `int`. If you only need to know whether the collection is empty, use `isEmpty()` instead.

Version: Java SE 21

Syntax

int size();

int count = collection.size();

Collection.size() is a method of the java.util.Collection interface. Call it on a collection, as in items.size(), with no arguments. It returns the element count as an int: 0 for an empty collection, or Integer.MAX_VALUE if the collection contains more than Integer.MAX_VALUE elements.

The method counts elements, not distinct values or reserved storage slots. If the collection allows duplicates, each occurrence counts separately. If you only need to know whether there are no elements, use items.isEmpty().

Calling size() does not change the collection. If the contents change, call it again to read the new count; a saved int does not update on its own. The method takes constant time on an ArrayList, but Collection does not guarantee that for every implementation.

Examples

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

public class CollectionSizeDemo {
    public static void main(String[] args) {
        Collection<String> items = new ArrayList<>();
        System.out.println(items.size());

        items.add("apple");
        items.add("apple");
        int savedSize = items.size();
        System.out.println(savedSize);

        items.remove("apple");
        System.out.println(items.size());
        System.out.println(savedSize);
    }
}

Result

0
2
1
2

The empty list has size `0`. Two occurrences of `"apple"` give a size of `2`. Removing one leaves `1` element, but `savedSize` is still `2`.

Related lessons

  • Java · Lesson 60 · Basic · Version: 2
  • Java · Lesson 61 · Basic · Version: 2

Sources