保持可变对象始终在TreeSet中排序 [英] Keeping mutable objects sorted in TreeSets at all times

查看:167
本文介绍了保持可变对象始终在TreeSet中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,如果稍后更改对象属性值,TreeSet不会按可变顺序保留可变对象。例如,

It came to my notice that a TreeSet doesn't keep the mutable objects in sorted order if object attribute values are changed later on. 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 + "]";
    }   
}

输出为:

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

在我更改特定学生的年龄,然后打印TreeSet后,Set似乎不再按排序顺序排列。为什么会这样?以及如何保持它总是排序?

After I change the age of a particular student, and then print the TreeSet, the Set seems no longer in sorted order. Why does this happen? and how to keep it sorted always?

推荐答案


为什么会发生这种情况? ?

Why does this happen?

因为该集不能监视所有对象的更改。 ..怎么能这样做?!

Because the set cannot monitor all its objects for changes... How would it be able to do that?!

HashSets 也出现同样的问题。当 HashSet 保存对象时,您无法更改影响对象哈希码的值。

Same problem arises for HashSets. You can't change values affecting an objects hash-code when a HashSet holds the object.


以及如何对其进行排序?

and how to keep it sorted always?

你通常从集合中删除元素,修改它,然后重新插入它。换句话说,更改

You typically remove the element from the set, modify it, and then reinsert it. In other words, change

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 <每次修改对象时,列表上都会显示/ code>。

You can also use for example a list, and call Collections.sort on the list each time you've modified an object.

这篇关于保持可变对象始终在TreeSet中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆