- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我注意到,如果稍后更改对象属性值,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/
我有一个包含一些宏和用户表单的 Excel 文件。 我不希望用户在没有密码的情况下访问文件本身。他们应该只能看到用户表单并通过用户表单输入数据。 这是我目前拥有的代码。 Private Sub Wor
我正在使用 ui 自动完成功能:over here 我需要始终打开自动完成功能,因此当单击正文中的某个位置时它不应该关闭。我已经用谷歌搜索过这个但我找不到任何东西。 最佳答案 抱歉,回复晚了! 我觉得
我有几个使用 Drupal 的站点,我有几个服务器,live,dev1,dev2... Drupal 的代码库存储库很大 (112Mb),所以我很想充分利用 git 的硬链接(hard link)功能
我需要一个始终保存 n 的数据结构迄今为止插入的最大项目(无特定顺序)。 所以,如果 n是 3,我们可以在下面的 session 中插入一些数字并且容器的内容发生变化: [] // now inse
这个问题在这里已经有了答案: Why don't flex items shrink past content size? (5 个答案) 关闭 5 年前。 我在 flexbox 中有 5 列 di
Smartgit 一直 pop 登录表单! 我已经在我的服务器上部署了 git。严格按照 git 设置的说明进行操作。 然后我用puttygen生成开放的SSH私钥,填写密码,把代码放在“public
我在对齐 div 时遇到问题。我在一个容器中有 5 个 div,全部向左浮动,按照下图设置。 每个 div 的宽度为 425px,div 与容器之间的边距始终为 15px,容器的宽度为 1350px。
我正在使用带有集成颠覆控制的 NetBeans。 如果我通过 TortoiseSVN 进行提交、添加等操作,NetBeans 将无法识别这些操作。 显然,如果我通过 NetBeans 进行更改,我的本
我知道有很多这样的问题,但我阅读了所有这些问题,其中没有一个解决了我的问题。下面我将展示我的 View 和 Controller 中的代码,以便您了解我的代码。 View :
我有一个 100% 高度的左浮动和 100% 的右浮动。一切正常,直到我用文本填充一侧,另一侧才会停止。 我该如何解决这个问题? 最佳答案 在为两列插入父 div 后,您可以使用 css 表。例如:
我使用此 JavaScript 代码是为了在验证失败后突出显示文本框和其他控件(在其上指定了 ASP.NET 验证器)。 $(document).ready(function() {
我是一名优秀的程序员,十分优秀!