java – 始终保持在TreeSet中排序的可变对象
发布时间:2020-12-14 05:23:31 所属栏目:Java 来源:网络整理
导读:我注意到,如果对象属性值稍后更改,则TreeSet不会按照排序顺序保持可变对象.例如, public class Wrap { static TreeSetStudent ts = new TreeSetStudent(new ComparatorStudent(){ @Override public int compare(Student o1,Student o2) { return o1.age - o2
我注意到,如果对象属性值稍后更改,则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后,该集合似乎不再处于排序顺序.为什么会这样呢?和如何保持排序总是? 解决方法
因为该集合不能监视所有对象的更改…如何才能做到这一点? HashSets出现同样的问题.当HashSet保存对象时,不能更改影响对象散列代码的值.
您通常从集合中删除元素,进行修改,然后重新插入.换句话说,改变 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |