Avatar ·

What is the difference between HashMap, LinkedHashMap and TreeMap in Java?

Hello everyone! I just started learning Java and encountered a problem when working with maps (Map). There are three main implementations: HashMap, LinkedHashMap and TreeMap. I read the documentation, but I don't fully understand when to use which one.

\n\n

For example, I have a task: I need to store a list of students with their IDs (key — Integer, value — String). I wrote this code:

\n\n
Map<Integer, String> students = new HashMap<>();\nstudents.put(3, "Anna");\nstudents.put(1, "Ivan");\nstudents.put(2, "Maria");\nSystem.out.println(students);
\n\n

The output turned out to be unordered: {1=Ivan, 2=Maria, 3=Anna}. Why doesn't the order match the insertion order? And what will happen if I replace HashMap with LinkedHashMap or TreeMap?

\n\n

Also I heard that they have different