Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Set.size(): Count the elements in a set

`Set.size()` returns how many elements the set currently holds, not how many times you tried to add one.

Version: Java SE 21

Syntax

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

Set.size is an instance method on the java.util.Set interface. The call set.size() takes no arguments, leaves the set unchanged, and returns its cardinality as an int. An empty set has size 0. If you only need to test whether the set is empty, use set.isEmpty().

A set does not store duplicates. In a HashSet, trying to add an element equal to one already present returns false and leaves the size unchanged. After processing input, size() therefore counts distinct stored values, not input entries. The size() method itself does not normalize the data.

If the set holds more than Integer.MAX_VALUE elements, size() returns Integer.MAX_VALUE. A result at that limit does not tell you whether the actual count is exactly that value or higher.

Examples

import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

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

        String[] input = {" Ada ", "ADA", "Lin", "Sam"};
        for (String name : input) {
            names.add(name.strip().toLowerCase(Locale.ROOT));
        }

        System.out.println(names.size());
    }
}

Result

0
3

The first line is `0` because the set is empty. `strip()` removes leading and trailing whitespace, and `toLowerCase(Locale.ROOT)` lowercases the text independently of the default locale. Both `" Ada "` and `"ADA"` become `"ada"`, so the second line is `3` after four add attempts.

Related lessons

  • Java · Lesson 5 · Advanced · Version: 2
  • Java · Lesson 8 · Advanced · Version: 2
  • Java · Lesson 27 · Basic · Version: 2
  • Java · Lesson 42 · Basic · Version: 2
  • Java · Lesson 4 · Intermediate · Version: 2
  • Java · Lesson 5 · Intermediate · Version: 2

Sources