Sorting a List of Complex Custom Objects in Java - NullPointerException in Comparator
I'm trying to sort a list of custom objects in Java, specifically instances of a class `Person` that contains a `String name` and an `Integer age`. My sorting logic is based on the `age` property, but I'm encountering a `NullPointerException` when some `Person` instances have null values for `age`. Here's a simplified version of my code: ```java import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Main { static class Person { String name; Integer age; Person(String name, Integer age) { this.name = name; this.age = age; } } public static void main(String[] args) { List<Person> people = new ArrayList<>(); people.add(new Person("Alice", 30)); people.add(new Person("Bob", null)); people.add(new Person("Charlie", 25)); Collections.sort(people, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return p1.age.compareTo(p2.age); } }); } } ``` When I run this code, it throws a `NullPointerException` on the line where I call `p1.age.compareTo(p2.age)`. I attempted to handle the null case by modifying the comparator, but it still resulted in an error. Here's an alternate attempt I made: ```java Collections.sort(people, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { if (p1.age == null && p2.age == null) return 0; if (p1.age == null) return 1; if (p2.age == null) return -1; return p1.age.compareTo(p2.age); } }); ``` This approach should technically work, but I'm still getting the same `NullPointerException`. I've also verified that the `age` field is indeed `null` for certain instances, as I expected. What am I missing here? Is there a more efficient way to handle sorting custom objects when dealing with potential `null` values? I'm using Java 11. For context: I'm using Java on macOS. Any ideas what could be causing this?