2

Does anyone know if it is possible to keep a TreeMap sorted in cases where I update one of my keys properties?

Lets suppose my key is sorted by property 'a', while b is used on equals():

class Key implements Comparable<Key> {
   int a;
   int b;
   // compareTo, equals end hashcode here
}

When key/value pairs are added, they will be sorted in a TreeMap, however how could I make sure the TreeMap will keep them sorted if I update one of these keys (property a)?

4
  • 10
    The only safe way is to remove the item, make the change and re-add it. Modifying keys or hashcodes in a data item invalidates the basic contract of consistency. Commented Jun 19, 2018 at 20:44
  • 1
    @Dragonthoughts you have a great comment - please add an answer :) Commented Jun 19, 2018 at 20:46
  • 1
    @user8035311 done, as requested :) Commented Jun 19, 2018 at 20:51
  • 2
    "sorting" by one column and checking equality by another may potentially be a big problem, because TreeMap and, say, HashMap will show different behavior. Commented Jun 19, 2018 at 20:56

2 Answers 2

8

The only safe way is to remove the item, make the change and re-add it. Modifying keys or hashcodes in a data item invalidates the basic contract of consistency.

Sign up to request clarification or add additional context in comments.

Comments

2

If you're relying on value semantics, then no. Maps in general tend to freak out if their keys are mutated. (TreeMap will often end up out of order, which may confound key lookups...and HashMap can break if hashCode() doesn't return a consistent value while the key is a key.) Any object used as a key ought to be immutable, or at the very least not modified.

If you want to update a key, it's better to remove the mapping and reinsert it under a new key with the values changed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.