user1911149
user1911149

Reputation: 13

How can I update values in a Map, maintaining the order

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?

Upvotes: 1

Views: 632

Answers (1)

JB Nizet
JB Nizet

Reputation: 691645

You should never modify keys stored in a map. Or at least not modify any of the fields used to implement equals() and hashCode() (in the case of a HashMap) or compareTo()/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.

Upvotes: 2

Related Questions