java – 始终保持在TreeSet中排序的可变对象

我注意到,如果对象属性值稍后更改,则TreeSet不会按照排序顺序保持可变对象.例如,
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 + "]";
    }   
}

输出为:

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

在更改特定学生的年龄,然后打印TreeSet后,该集合似乎不再处于排序顺序.为什么会这样呢?和如何保持排序总是?

解决方法

Why does this happen?

因为该集合不能监视所有对象的更改…如何才能做到这一点?

HashSets出现同样的问题.当HashSet保存对象时,不能更改影响对象散列代码的值.

and how to keep it sorted always?

您通常从集合中删除元素,进行修改,然后重新插入.换句话说,改变

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

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

您也可以使用列表,并在每次修改对象时在列表中调用Collections.sort.

相关文章

背景 阿里java开发规范是阿里巴巴总结多年来的最佳编程实践,...
# 前言 在面试这一篇我们介绍过[CountDownLatch和CyclicBarr...
多线程编程是每一个开发必知必会的技能,在实际项目中,为了...
背景 在我们系统中有这么一个需求,业务方会通过mq将一些用户...
# 前言 为了更好的进行开发和维护,我们都会对程序进行分层设...
前言 关于动态代理的一些知识,以及cglib与jdk动态代理的区别...