CodexBloom - Programming Q&A Platform

How can I implement a custom comparator for sorting objects in a Java TreeSet?

👀 Views: 269 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
java treeset comparator sorting Java

I'm relatively new to this, so bear with me. I'm collaborating on a project where Hey everyone, I'm running into an issue that's driving me crazy... I'm trying to store a set of custom objects in a `TreeSet` in Java, but I need to sort them based on multiple attributes. My custom object is called `Person`, which has attributes like `name` (String) and `age` (int). I want to sort primarily by `age` and secondarily by `name` in case of age ties. I've attempted to implement a custom comparator, but I keep getting `ClassCastException` when trying to add elements to the set. Here's my code snippet: ```java import java.util.Comparator; import java.util.TreeSet; class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } } class PersonComparator implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { if (p1.age != p2.age) { return Integer.compare(p1.age, p2.age); } return p1.name.compareTo(p2.name); } } public class Main { public static void main(String[] args) { TreeSet<Person> people = new TreeSet<>(new PersonComparator()); people.add(new Person("Alice", 30)); people.add(new Person("Bob", 25)); people.add(new Person("Charlie", 25)); for (Person p : people) { System.out.println(p.name + " " + p.age); } } } ``` When I run this code, I get the following behavior: `Exception in thread "main" java.lang.ClassCastException: Person want to be cast to Person`. I'm using Java 11. I've also checked for null values but didn't find any. What could be causing this scenario and how can I fix it to ensure that my `TreeSet` sorts properly? Am I missing something obvious? Thanks for any help you can provide!