Home Java HashSet Methods size() Java HashSet size() Method 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.
Set<String> fruit = new HashSet<>();
fruit.add("apple");
fruit.add("apple");
System.out.println(fruit.size()); // 1 Call What 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.util.HashSet<E>
public int size()
// Declared in Set<E> and Collection<E> Parameters Parameter Description None size() takes no parameters.
Return Value Return Value Description intThe number of elements in the set. Very large sets report Integer.MAX_VALUE.
Compare with Similar Methods Counting in other places:
Method How 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 1. Grows with distinct adds 2. Count distinct letters 3. Size vs capacity, and null Example 1 — Watch the Size Change as You Add and Remove Print the size after each step of a small shopping list.
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());
}
} start: 0
after two adds: 2
after a repeat: 2
after a removal: 1 How It Works Born empty. A new HashSet has no elements, so the size begins at 0.Two different fruits. "apple" and "pear" are distinct, so the size becomes 2.A repeat is ignored. Adding "apple" a second time does not store anything new, so the size stays at 2.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.
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");
}
}
} banana: 3 different letters
mississippi: 4 different letters
level: 3 different letters How It Works Boxing chars. Each char is autoboxed to a Character as it goes into the set.banana. The letters are b, a, n, a, n, a, which leaves three distinct values.mississippi. Eleven characters reduce to m, i, s, and p, so the size is 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.
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());
}
} capacity hint 100, size: 0
with a null: 3
second null: 3
isEmpty: false How It Works A hint, not content. The 100 only prepares room for a lot of elements, so size() reports 0.null is an element. After "a", "b", and null, the set holds three elements.Only one null. A second add(null) finds the first one, so nothing changes and the size stays 3.Not empty. With three elements stored, isEmpty() is false.Frequently Asked Questions How do I get the number of elements in a HashSet? Call set.size(). It returns an int with the number of distinct elements currently in the set.
Does size() count duplicates? No. A set stores each element once, so adding a duplicate does not change the size.
Is HashSet size() slow for big sets? No. It runs in constant time because the set keeps a running count of its elements.
What is the difference between size and capacity? Size is the number of stored elements. Capacity is the number of internal buckets, an implementation detail that HashSet manages for you.
Does null count in size()? Yes. If you add null, the set holds it as one element and size() includes it.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion