Search code examples
javaooptreenode

Does a TreeMap change ordering dynamically?


Let's say I put in an entry in to my map which holds an object as a key:

treeNode.put(someObject,someValue); 

then some time later I get that entry, and change the object so that now if resorted it lands somewhere else in the map.

treeNode.get(someObject); 
someObject.change();

Do I have to remove the old entry in the map, and put again for the map to remain consistent with the new key?


Solution

  • Yes, you do. There is no possible way for TreeMap to know that a value's position in the map should have changed.

    TreeMap doesn't say this in so many words, but Map specifies that

    The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.

    and TreeMap documents that it uses the specified comparator instead of equals.