Does a HashMap retain the order of its elements on the next read if it is constructed and "filled" as a LinkedHashMap?
Suppose I have a Java method that 开发者_高级运维returns a HashMap object.
Because a LinkedHashMap is a subclass of HashMap, I can return a LinkedHashMap from this method just fine.
On the next "read" action (no adding/removing/modifying of K/V pairs), would iterating over the keys of the resulting method (which returns a HashMap) go in the same order as the originating LinkedHashMap, even though the HashMap lacks the key links?
Yes. The actual instance of the object is still the returned LinkedHashMap
, therefore it will have its iterating order.
However, I wouldn't depend on this for anything. Why are you using HashMap
s if iterating order is important? This might be a code smell.
精彩评论