views:

134

answers:

1

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?

+8  A: 

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.

Ben S
Yeah, its kind of a silly question. I'm not actually using it for anything - I was just fooling around with some new ideas for a project I'm developing for and the question occurred to me. Seems like it might be useful to know the answer to at some point, though to be honest I have no idea why now.
javanix