开发者

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 HashMaps if iterating order is important? This might be a code smell.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜