Why is the output of for HashMap keySet misordered?


#1

In the final exercise, why does:
HashMap majorCities = new HashMap();
majorCities.put("New York", 1624);
majorCities.put("London", 43);
majorCities.put("Mexico City", 1521);
majorCities.put("Sao Paulo", 1554);
for (String city : majorCities.keySet() ) {
System.out.println(city + " was founded in " + majorCities.get(city));
}

Produce:
New York was founded in 1624
London was founded in 43
Sao Paulo was founded in 1554
Mexico City was founded in 1521

Instead of the order it was loaded:
New York was founded in 1624
London was founded in 43
Mexico City was founded in 1521
Sao Paulo was founded in 1554

?


#2

Hi @davidendry ,

The items in a HashMap are not necessarily stored in the same order in which they were added. They are stored using an algorithm that is designed to optimize efficiency of retrieval.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.