Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

HashSet.size() — count the elements in a set

`size()` returns the current number of elements in a `HashSet` as an `int`. Adding an element that is already present does not increase the count.

Version: Java SE 21

Syntax

public int size()

// Call on a java.util.HashSet instance:
int count = set.size();

HashSet.size() is a no-argument instance method of java.util.HashSet in Java SE 21. Call it on a set, for example int count = colors.size();. It returns the number of elements present at the time of the call as an int, without modifying the set. An empty set returns 0.

The method counts elements, not calls to add() or the capacity of the backing hash table. If an equal element is already present, add() returns false and the size stays the same. HashSet permits null; if present, it counts as one element.

After removing an element that was present, the next call returns one less. A previously stored count does not update automatically. If you only need to check whether the set is empty, use isEmpty().

Examples

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<String> colors = new HashSet<>();
        System.out.println(colors.size());

        colors.add("red");
        colors.add("blue");
        System.out.println(colors.size());

        colors.add("red");
        System.out.println(colors.size());

        colors.remove("blue");
        System.out.println(colors.size());
    }
}

Result

0
2
2
1

The empty set contains `0` elements. Adding `"red"` and `"blue"` brings the count to `2`. Adding `"red"` again leaves it at `2`; removing `"blue"` brings it down to `1`.

Related lessons

  • Java · Lesson 55 · Basic · Version: 2

Sources