3

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?

user2763361
  • 3,789
  • 11
  • 45
  • 81

2 Answers2

3

Yes

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

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • I also need an immutable TreeMap but it seems that Collections.unmodifiableMap(treeMap) returns a map, not a treemap. So, when I ask for the keySet I get a set, which does not have an ordering. Please would you elaborate for me? – Robino Jun 24 '16 at 18:00
  • @Robino A `Set` is not _guaranteed_ to have an order, but of course it can a `TreeSet` is a `Set` **and** has an order. If the issue is that you need methods from the `NavigableSet` `interface` then that's a different issue. – Boris the Spider Jun 24 '16 at 18:04
2

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.

lukens
  • 479
  • 4
  • 10
  • Linking to grepcode can show that the [call](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Collections.java#Collections.unmodifiableMap%28java.util.Map%29) just is a call to the [constructor](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Collections.java#Collections.UnmodifiableMap) that has that parameter just sitting there with all of the other things throwing exceptions. –  Sep 09 '14 at 16:39