1. Introduction
TreeSet is a part of Java’s collections framework that represents a set implemented using a Red-Black tree. While TreeSet readily handles predefined data types like integers and strings, handling user-defined objects requires a bit more effort. For TreeSet to manage these objects, they must be comparable. This post demonstrates how to use TreeSet with user-defined objects by making them implement the Comparable interface.
2. Program Steps
1. Define a Person class that implements the Comparable interface.
2. Override the compareTo() method for the Person class to define natural ordering.
3. Create a TreeSet and add Person objects to it.
4. Display the sorted set.
3. Code Program
import java.util.TreeSet;
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person otherPerson) {
return this.age - otherPerson.age; // Sorting based on age
}
@Override
public String toString() {
return name + ": " + age;
}
}
public class TreeSetWithObjects {
public static void main(String[] args) {
TreeSet<Person> persons = new TreeSet<>();
persons.add(new Person("John", 25));
persons.add(new Person("Alice", 22));
persons.add(new Person("Bob", 29));
System.out.println("Sorted persons based on age:");
for (Person person : persons) {
System.out.println(person);
}
}
}
Output:
Sorted persons based on age: Alice: 22 John: 25 Bob: 29
4. Step By Step Explanation
Step 1: We define a Person class with attributes name and age. This class implements the Comparable interface which mandates the overriding of compareTo() method.
Step 2: In the compareTo() method, we have defined the natural ordering for Person objects based on their age. The subtraction method used here ensures that the TreeSet will sort the Person objects in ascending order of their age.
Step 3: We then create a TreeSet of Person objects and add three objects to it.
Step 4: When we iterate over the TreeSet, it displays the Person objects in ascending order of their age, demonstrating that the compareTo() method has been effectively utilized.
By following this approach, you can leverage TreeSet's sorting capability for any custom object by ensuring the object class implements the Comparable interface and provides a meaningful definition for the compareTo() method.