A newbie question perhaps, what happens if I change an element in a TreeSet, while traversing it? Would this lead to re-ordering of the element in the set?
Asked
Active
Viewed 236 times
2
-
2Well, try it and see:) Also, if by traversal you mean iterate through with an iterator and by change you mean add/delete, then read http://stackoverflow.com/questions/6460320/using-iterator-on-a-treeset – zw324 Apr 25 '13 at 14:30
-
1The examples there are adding/removing an element. What if I modify the element itself, while iterating? (I am trying in the mean while :)) – u07103 Apr 25 '13 at 14:38
-
well, you have a nice answer now:) +1 for trying it out. – zw324 Apr 25 '13 at 14:38
1 Answers
2
Would this lead to re-ordering of the element in the set?
No, mutating an element inside a set does not lead to re-ordering of the tree set. You should never do that, because once you make a mutation that changes the order, your element may get lost in the tree. What you should do is removing the element, mutating its properties that change ordering, and then re-inserting it back.
Consider this example class:
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);
}
}
If you make a tree set like this
TreeSet<Student,Integer> gradeInMath = ...
and then decide to change student's name when it's already in the set, you should do it like this:
Student nameChangeStudent = new Student("Joe");
Integer theGrade = gradeInMath.remove(nameChangeStudent);
nameChangeStudent.setName("Jack");
gradeInMath.put(nameChangeStudent, theGrade);
As you can see, this is not pretty at all. That's why as a general rule you should prefer immutable keys for your maps, both hash-based and tree-based.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523