作者:平淡人生路20111212 | 来源:互联网 | 2022-10-29 20:02
If two hashmaps have exact same set of key-value pairs, will I always get data in same order while iterating on two hashmaps?
Map map1 = new HashMap<>();
Map map2 = new HashMap<>();
map1.put("a1","b1");
map1.put("a2","b2");
map1.put("a3","b3");
map2.put("a1","b1");
map2.put("a2","b2");
map2.put("a3","b3");
for (Map.Entry e : map1.entrySet()) {
System.out.println(e.getKey());
}
for (Map.Entry e : map2.entrySet()) {
System.out.println(e.getKey());
}
If map1's iteration look like (a1,a2,a3), will map2's iteration also be like (a1,a2,a3)?
I know that bucket index is calculated using hash of key, but I am not sure if same index will be returned always.
1> 小智..:
You can never rely on order in case of Hashmap.If you want to maintain insertion order use LinkedHashMap and for sorted order use TreeMap