gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:21:51 25 4
gpt4 key购买 nike

我注意到,如果稍后更改对象属性值,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=15], Student [age=30], Student [age=50]]

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

最佳答案

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 - 始终保持可变对象在 TreeSet 中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8030016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com