Java HashSet size() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In Java, size() returns the number of elements currently stored in a HashSet. Because a set holds no duplicates, adding the same value again never changes the result.

The count includes null if it was added. It is the number of elements, not the number of internal buckets, so a freshly created set always has size 0.

An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety.

Syntax

No arguments; returns an int.

Java
Set<String> fruit = new HashSet<>();
fruit.add("apple");
fruit.add("apple");
System.out.println(fruit.size());   // 1
CallWhat it does
set.size()The number of distinct elements.
set.size() == 0Works, but isEmpty() reads better.
new String[set.size()]Sizes an array to hold every element.
set.size() > limitA quick limit check.

Passing a number to the constructor, as in new HashSet<>(100), only suggests an initial capacity. The size still starts at 0.

Library declarations
Java
// java.util.HashSet<E>
public int size()

// Declared in Set<E> and Collection<E>

Parameters

ParameterDescription
Nonesize() takes no parameters.

Return Value

Return ValueDescription
intThe number of elements in the set. Very large sets report Integer.MAX_VALUE.

Compare with Similar Methods

Counting in other places:

MethodHow it differs
isEmpty()A direct yes/no for "no elements".
toArray()Its array length equals the set size at that moment.
ArrayList.size()Counts every element of a list, duplicates included.
String.length() and array.lengthOther collections use different names for the count.

Java Examples

Example 1 — Watch the Size Change as You Add and Remove

Print the size after each step of a small shopping list.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetSizeDemo {
    public static void main(String[] args) {
        Set<String> fruit = new HashSet<>();
        System.out.println("start: " + fruit.size());

        fruit.add("apple");
        fruit.add("pear");
        System.out.println("after two adds: " + fruit.size());

        fruit.add("apple");
        System.out.println("after a repeat: " + fruit.size());

        fruit.remove("pear");
        System.out.println("after a removal: " + fruit.size());
    }
}

How It Works

  1. Born empty. A new HashSet has no elements, so the size begins at 0.
  2. Two different fruits. "apple" and "pear" are distinct, so the size becomes 2.
  3. A repeat is ignored. Adding "apple" a second time does not store anything new, so the size stays at 2.
  4. Removal shrinks it. Taking "pear" out leaves one element.

Example 2 — Count the Different Letters in a Word

Add every character of a word to a set and use size() as the count of distinct letters.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetSizeLetters {
    static int differentLetters(String word) {
        Set<Character> letters = new HashSet<>();
        for (char c : word.toCharArray()) {
            letters.add(c);
        }
        return letters.size();
    }

    public static void main(String[] args) {
        String[] words = {"banana", "mississippi", "level"};
        for (String word : words) {
            System.out.println(word + ": " + differentLetters(word) + " different letters");
        }
    }
}

How It Works

  1. Boxing chars. Each char is autoboxed to a Character as it goes into the set.
  2. banana. The letters are b, a, n, a, n, a, which leaves three distinct values.
  3. mississippi. Eleven characters reduce to m, i, s, and p, so the size is 4.
  4. level. The word reads the same backwards and has only l, e, and v, so the count is 3.

Example 3 — Size Is Not Capacity, and null Counts

Create a set with a large capacity hint, then add a null twice.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetSizeCapacity {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>(100);
        System.out.println("capacity hint 100, size: " + set.size());

        set.add("a");
        set.add("b");
        set.add(null);
        System.out.println("with a null: " + set.size());

        set.add(null);
        System.out.println("second null: " + set.size());
        System.out.println("isEmpty: " + set.isEmpty());
    }
}

How It Works

  1. A hint, not content. The 100 only prepares room for a lot of elements, so size() reports 0.
  2. null is an element. After "a", "b", and null, the set holds three elements.
  3. Only one null. A second add(null) finds the first one, so nothing changes and the size stays 3.
  4. Not empty. With three elements stored, isEmpty() is false.

Frequently Asked Questions

Call set.size(). It returns an int with the number of distinct elements currently in the set.
No. A set stores each element once, so adding a duplicate does not change the size.
No. It runs in constant time because the set keeps a running count of its elements.
Size is the number of stored elements. Capacity is the number of internal buckets, an implementation detail that HashSet manages for you.
Yes. If you add null, the set holds it as one element and size() includes it.

Next: spliterator()

Get a Java 8 Spliterator that can step or split.

spliterator() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful