Does the HashMap preserve the order of its elements in the next reading if it is constructed and "populated" like a LinkedHashMap?

Suppose I have a Java method that returns a HashMap object.

Since LinkedHashMap is a subclass of HashMap, I can return LinkedHashMap from this method just fine.

On the next read action (without adding / removing / modifying the K / V pairs), iterating over the keys of the resulting method (which returns the HashMap) will go in the same order as the original LinkedHashMap, even though the HashMap is missing key references?

+2


a source to share


1 answer


Yes. The actual object instance is still returned LinkedHashMap

, so it will have its own iteration order.



However, I will never depend on it. Why do you use HashMap

if iteration order is important? It could be a code smell.

+10


a source







All Articles