我注意到,如果对象属性值稍后更改,则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);