5

Does Colelction.unmodifiableMap safeguard the iteration order?

I was trying newMap.put(key,Collections.ModifiableMap(oldMap)) Then when I do newMap.get(key) and iterate, iterate order seems to change.

How can we protect the iterate order?

Chandra
  • 777
  • 3
  • 12
  • 18

3 Answers3

5

UnmodifiableMap simply delegates all methods, except writing ones. It's order is exactly that of the delegate.

If you need to have the same order as the first collection, use LinkedHashMap.

Lundberg
  • 404
  • 3
  • 4
4

Check out Collections.unmodifiableSortedMap. That should provide you with a read-only view on your Map and maintain the sorted order of the keys.

Sanghyun Lee
  • 21,644
  • 19
  • 100
  • 126
Kenny Wyland
  • 20,844
  • 26
  • 117
  • 229
  • 2
    The author only mentioned this in the comments, but he is using LinkedHashMap, which has a different iteration order from a SortedMap. `Collections.unmodifiableSortedMap` returns `method unmodifiableSortedMap in class java.util.Collections cannot be applied to given types; [ERROR] required: java.util.SortedMap [ERROR] found: java.util.LinkedHashMap [ERROR] reason: cannot infer type-variable(s) K,V [ERROR] (argument mismatch; java.util.LinkedHashMap cannot be converted to java.util.SortedMap)` – yegeniy Apr 21 '15 at 14:26
1

If we look at the source for Collections.unmodifiableMap, we see that it just passes it to an UnmodifiableMap class, who simply wraps it. So it makes no changes to the underlying map's order.

And according to the documentation for unmodifiableMap it says it:

Returns an unmodifiable view of the specified map.

Since it says it returns a view, it is implying that we're not getting a different map, just a different way to access the old map.

Zach L
  • 16,072
  • 4
  • 38
  • 39