Course contentsShow
← Java
Lesson 1074 of 2,87025. Set ImplementationsFree lesson

Null Elements: TreeSet's Null Intolerance

Learn why TreeSet cannot contain null elements and throws NullPointerException when null is added.

Null Elements: TreeSet's Null Intolerance

What you'll learn: You'll discover why TreeSet rejects null elements and throws a NullPointerException when you try to add them.

The Core Problem

TreeSet maintains sorted order by comparing elements using their compareTo method (from the Comparable interface). But here's the issue: you cannot call a method on null. When TreeSet tries to insert an element, it must compare it with existing elements to find the correct sorted position. If you pass null, TreeSet attempts to call null.compareTo(...), which immediately triggers a NullPointerException.

Think of it like trying to alphabetize a book that doesn't exist. You can't determine where to place "nothing" in an ordered sequence because you need actual properties to compare.

Why This Differs from HashSet

You might remember that HashSet (which you learned earlier) can contain one null element. That's because HashSet doesn't need to compare elements—it just uses hash codes and equality checks. TreeSet, however, requires comparison, and comparison requires actual objects with a compareTo method.

What Happens When You Try

TreeSet<String> names = new TreeSet<>();
names.add("Alice");
names.add("Bob");
names.add(null);  // NullPointerException thrown here!

The moment you call add(null), TreeSet tries to compare null with "Alice" or "Bob" to determine placement, and the attempt to invoke null.compareTo(...) fails instantly.

The Bottom Line

TreeSet's sorted nature is incompatible with null elements because sorting requires comparison, and comparison requires actual objects.

Key Takeaway: TreeSet cannot contain null elements because it needs to call compareTo on every element to maintain sorted order, and calling methods on null throws a NullPointerException.