How does TreeSet sort objects

TreeSet can sort objects by passing in Comparator. When an instance is created using the TreeSet default constructor, elements must implement the Comparable interface to provide natural ordering. If the element does not implement the Comparable interface, sorting can be achieved by passing in a Comparator object when creating a TreeSet instance.

For example, suppose there is a Student class:

public class Student {
    
    
    private int id;
    private String name;
    private int age;

    // constructor, getters, and setters omitted for brevity

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

You can implement a Comparator that sorts by age in ascending order:

import java.util.Comparator;

public class AgeComparator implements Comparator<Student> {
    
    
    @Override
    public int compare(Student s1, Student s2) {
    
    
        return s1.getAge() - s2.getAge();
    }
}

Then, pass in AgeComparator when creating a TreeSet instance to sort in ascending order of age:

import java.util.TreeSet;

public class TreeSetExample {
    
    
    public static void main(String[] args) {
    
    
        TreeSet<Student> studentSet = new TreeSet<>(new AgeComparator());
        studentSet.add(new Student(1, "Alice", 18));
        studentSet.add(new Student(2, "Bob", 20));
        studentSet.add(new Student(3, "Charlie", 19));
        System.out.println(studentSet);
    }
}

The output is:

[Student{id=1, name='Alice', age=18}, Student{id=3, name='Charlie', age=19}, Student{id=2, name='Bob', age=20}]

Guess you like

Origin blog.csdn.net/qq_42133976/article/details/130417295