Question

Suppose I have a TreeMap<Long,Long> map. I need to view an unmodifiable version from a getter so I return a Map<Long,Long> of return Collections.unmodifiableMap(map);.

However, I need it to be returned with the same ordering of keys as it was when it was a TreeMap<Long,Long>. Can I be guaranteed in all cases that the ordering of the keys will be the same in this unmodifiable Map when created from a TreeMap?

Was it helpful?

Solution

Yes

It's a view. The underlying data structure is the same.

OTHER TIPS

The unmodifiable map is just a wrapper around the original map that throws exceptions when a mutator is called, all other methods are effectively proxies to the source map.

It is worth noting that though the view is unmodifiable, the underling map can still be mutated and these mutations will be reflected in the view. Bugs can be introduced by developers thinking the unmodifiable map is an immutable copy of the original map, rather than simply an unmodifiable view of it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top