也许是一个新手问题,如果我在遍历 TreeSet 时更改其中的元素会发生什么?这会导致集合中元素的重新排序吗?
最佳答案
Would this lead to re-ordering of the element in the set?
不,改变集合内的元素不会导致树集合的重新排序。你永远不应该这样做,因为一旦你进行了改变顺序的突变,你的元素可能会在树中丢失。您应该做的是删除该元素,改变其改变顺序的属性,然后将其重新插入回来。
考虑这个示例类:
class Student : Comparable<Student> {
private String name;
public Student(String name) {this.name = name;}
public final String getName() {return name;}
public final void setName(String name) { this.name = name;}
public int compareTo<Student>(Student other) {
return name.compareTo(other.name);
}
}
如果你制作这样的树集
TreeSet<Student,Integer> gradeInMath = ...
然后决定更改学生的姓名(当学生的姓名已在集合中时),您应该这样做:
Student nameChangeStudent = new Student("Joe");
Integer theGrade = gradeInMath.remove(nameChangeStudent);
nameChangeStudent.setName("Jack");
gradeInMath.put(nameChangeStudent, theGrade);
正如您所看到的,这根本不漂亮。这就是为什么作为一般规则,您应该更喜欢映射的不可变键,基于散列和基于树。
关于java - 遍历时元素发生变化时 Treeset 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16217503/