I'm learning about HashMaps in Java and I'm confused about the iteration order. The documentation states that HashMap doesn't guarantee any specific iteration order, but in my simple test, the order seems to remain consistent:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. Java 11 Docs
import java.util.HashMap; public class HashMapDemo { public static void main(String[] args) { HashMap<String, String> dishes = new HashMap<>(); // Adding more elements with complex keys dishes.put("dish-1234", "Pho"); dishes.put("dish-5678", "Spicy Beef Noodle Soup"); dishes.put("dish-9012", "Broken Rice"); dishes.put("dish-3456", "Banh Mi"); dishes.put("dish-7890", "Hu Tieu"); dishes.put("dish-2345", "Mi Quang"); dishes.put("dish-6789", "Crab Noodle Soup"); dishes.put("dish-0123", "Rolled Rice Cake"); System.out.println("First time:"); dishes.forEach((id, name) -> System.out.println(id + ": " + name)); // Create new HashMap with same data HashMap<String, String> dishes2 = new HashMap<>(); dishes2.putAll(dishes); System.out.println("\nSecond time (New HashMap):"); dishes2.forEach((id, name) -> System.out.println(id + ": " + name)); } } Output:
First time: dish-7890: Hu Tieu dish-3456: Banh Mi dish-2345: Mi Quang dish-1234: Pho dish-0123: Rolled Rice Cake dish-5678: Spicy Beef Noodle Soup dish-9012: Broken Rice dish-6789: Crab Noodle Soup Second time (New HashMap): dish-7890: Hu Tieu dish-3456: Banh Mi dish-2345: Mi Quang dish-1234: Pho dish-0123: Rolled Rice Cake dish-5678: Spicy Beef Noodle Soup dish-9012: Broken Rice dish-6789: Crab Noodle Soup I understand that if I need guaranteed order, I should use LinkedHashMap or TreeMap, but I'm trying to understand the actual behavior of HashMap. I read some documentation talk about re-size and re-hashing, maybe it's too hard to understand for me.
I also read some post say this problem, but I can not re-produce
- Why HashMap does not guarantee that the order of the map will remain constant over time
- Cause of the difference in the insertion order of HashMap and LinkedHashMap
How can I understand this?

"seven") changes the output order: IDEone inserting up to"six"does not change the order of previous elements (relative to each other, maybe the new element is inserted (in iterator order) between two existing ones, but after inserting"seven"the order of previous elements is changed (e.g."four"and"one"were last , moved to 2nd and 3rd position) - certainly additional buckets were createdHashMap<String, String> dishes2 = new HashMap<>(2000);