微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐