Java – always keep the mutable objects sorted in the TreeSet

I noticed that TreeSet does not keep mutable objects in sort order if the object property value changes later For example,

public class Wrap { 
    static TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){
        @Override
        public int compare(Student o1,Student o2) {            
            return o1.age - o2.age;
        }       
    }); 
    public static void main(String []args){
        Student s = new Student(10);
        ts.add(s); 
        ts.add(new Student(50));
        ts.add(new Student(30));
        ts.add(new Student(15));
        System.out.println(ts);
        s.age = 24;      //Here I change the age of a student in the TreeSet
        System.out.println(ts);     
    }
}
class Student{
    int age;
    Student(int age){
        this.age = age;
    }   
    @Override
    public String toString() {
        return "Student [age=" + age + "]";
    }   
}

Output is:

[Student [age=10],Student [age=15],Student [age=30],Student [age=50]]
[Student [age=24],Student [age=50]]

After changing the age of a particular student and printing the TreeSet, the collection no longer appears to be in sort order Why? And how to keep sorting always?

Solution

Because the collection cannot monitor changes to all objects... How can this be done?

Hashsets has the same problem When a HashSet saves an object, you cannot change the value that affects the object hash code

You usually delete elements from the collection, modify them, and then reinsert them In other words, change

s.age = 24;      //Here I change the age of a student in the TreeSet

to

ts.remove(s);
s.age = 24;      //Here I change the age of a student in the TreeSet
ts.add(s);

You can also use the list and call Collections. in the list every time you modify the object. sort.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>