Witam,
Ostatio czytałem na temat Map w Javie i chciałem przetestować działanie różnych implementacji. W skrócie:
HashMap - nie gwarantuje kolejności elementów
TreeMap - sortuje według komparatora
LinkedHashMap - dane są przechowywane w takiej samej kolejności w jakiej je dodano
Pozwoliłem sobie to sprawdzić i napisałem krótki kod:
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<>();
Map<Integer, String> treeMap = new TreeMap<>();
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
insertToMap(hashMap);
insertToMap(treeMap);
insertToMap(linkedHashMap);
showContent(hashMap);
showContent(treeMap);
showContent(linkedHashMap);
}
private static void showContent(Map<Integer, String> map) {
System.out.println("\n" + map.getClass().getName());
for(Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println( entry.getKey() + " " + entry.getValue());
}
}
private static void insertToMap(Map<Integer, String> map) {
map.put(2, "Dwa");
map.put(3, "trzy");
map.put(9, "dziesiec");
map.put(1, "jeden");
map.put(7, "siedem");
map.put(8, "osiem");
map.put(5, "piec");
}
i wynik:
java.util.HashMap
1 jeden
2 Dwa
3 trzy
5 piec
7 siedem
8 osiem
9 dziesiec
java.util.TreeMap
1 jeden
2 Dwa
3 trzy
5 piec
7 siedem
8 osiem
9 dziesiec
java.util.LinkedHashMap
2 Dwa
3 trzy
9 dziesiec
1 jeden
7 siedem
8 osiem
Według LinkedHashMap i TreeMap wszystko wygląda dobrze, ale zastanawia mnie dlaczego w HashMap zawartośc jest posortowana względem klucza, skoro tutaj nie ma żadnej gwarancji że tak będzie?