I have a TreeMap with a custom Comparator. I want to update one of the values of the Map, but if the fields checked by the Comparator are changed, does the Map keep its order?
I have a TreeMap with a custom Comparator . I want to update one
Share
You should never modify keys stored in a map. Or at least not modify any of the fields used to implement
equals()andhashCode()(in the case of a HashMap) orcompareTo()/compare()(in the case of a SortedMap).This will put the map in an inconsistent state, and you can’t expect it to work reliably after doing that.
Of course, you can remove the key from the map, modify it, and then reinsert it.
But you’d better use immutable types as keys of your maps, to avoid shooting yourself in the foot.