As a general rule, it is not recommended to βmodifyβ any types of values ββadded to Java containers that rely on equality, a hash code, etc., given that none of the known standard containers performs automatic balancing or tuning in response to a change values ββ(which makes sense).
Along with Set this rule is equally true for Map types. If you iterate over the map and change the "key" in place, everything goes wrong. For this reason, it is recommended to use immutable types as the keys of your map (think of String , Integer , etc.). Your example can be demonstrated with a simple example:
public class Test { public static void main(final String[] args) { Mutable m1 = new Mutable(1); Mutable m2 = new Mutable(2); Mutable m3 = new Mutable(3); Mutable m4 = new Mutable(4); TreeSet<Mutable> ts = new TreeSet<Mutable>(new Cmp()); ts.add(m1); ts.add(m2); ts.add(m3); ts.add(m4); System.out.println(ts); for (Iterator<Mutable> iter = ts.iterator(); iter.hasNext(); ) { Mutable m = iter.next(); if (mi == 1 || mi == 3) { mi = mi + 10; } } System.out.println(ts); } } class Mutable { public int i; public Mutable(int i) { this.i = i; } public String toString() { return "Mutable[" + i + "]"; } } class Cmp implements Comparator<Mutable> { @Override public int compare(Mutable o1, Mutable o2) { return Integer.valueOf(o1.i).compareTo(Integer.valueOf(o2.i)); } } Output: [Mutable[1], Mutable[2], Mutable[3], Mutable[4]] [Mutable[11], Mutable[2], Mutable[13], Mutable[4]]
source share