user2133121
user2133121

Reputation: 401

When are TreeMap and ConcurrentSkipListMap sorted?

I have a Map for which I provide a key class for which I've implemented a comparitor. The comparitor is partly time-based, so the order may change as time marches on. The question is: when is the comparison between objects done, at insertion time into the map or at iterator creation time?

Upvotes: 0

Views: 57

Answers (1)

Andreas
Andreas

Reputation: 159096

The tree is built on insert.

Also, be aware of the following warning in the javadoc of Map:

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of a [key] object is changed in a manner that affects equals comparisons while the object is a key in the map.

So, the compare method should be stable, i.e. should not change because of the progression of time.

Any time a key changes, it must be removed before the change, and re-added after the change.

Upvotes: 4

Related Questions