CodexBloom - Programming Q&A Platform

Java 17: NullPointerException when using custom Comparator with TreeSet and null values

👀 Views: 56 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
java comparator treeset nullpointerexception Java

I've been researching this but I'm following best practices but I'm working with a `NullPointerException` when trying to use a custom `Comparator` with a `TreeSet` in Java 17... The goal is to sort a collection of objects that can contain `null` values, but I need to seem to handle them appropriately in my comparator. Here's the relevant code snippet: ```java import java.util.TreeSet; import java.util.Comparator; class Person { String name; Integer age; Person(String name, Integer age) { this.name = name; this.age = age; } } Comparator<Person> personComparator = new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { if (p1 == null && p2 == null) return 0; if (p1 == null) return 1; // Nulls should be considered "greater" if (p2 == null) return -1; return p1.age.compareTo(p2.age); } }; TreeSet<Person> people = new TreeSet<>(personComparator); people.add(new Person("Alice", 30)); people.add(new Person("Bob", null)); people.add(null); // Adding a null value people.add(new Person("Charlie", 25)); ``` When I run this code, I get a `NullPointerException` on the line where I add a `Person` object with a null age. It seems to occur when the `compare` method tries to call `compareTo` on a null `Integer`. I've tried adding null checks to handle null ages, like this: ```java if (p1.age == null && p2.age == null) return 0; if (p1.age == null) return 1; // Null age is considered greater if (p2.age == null) return -1; ``` However, this still doesn't resolve the scenario, and I still get the `NullPointerException`. I also explored using `Comparator.nullsLast()` but wasn't sure how to integrate it in this context. What am I missing here? How can I safely handle null values in both the `TreeSet` and my custom comparator without running into exceptions? Thanks in advance! Could this be a known issue?