Sobes.tech
Junior — Middle

What are the differences between the implementations of the Map interface: HashMap and TreeMap, and in which cases is it preferable to use each of them?

sobes.tech AI

Answer from AI

HashMap and TreeMap are two implementations of the Map interface in Java, differing in data structure and behavior:

  • HashMap:

    • Based on a hash table.
    • Allows storing key-value pairs without order.
    • Fast access (average O(1)) to elements by key.
    • Allows null as a key and value.
  • TreeMap:

    • Based on a red-black tree (a balanced tree).
    • Stores elements in sorted order by key.
    • Access to elements in O(log n).
    • Does not allow null as a key (throws NullPointerException).

When to use:

  • If access speed is important and order does not matter — HashMap.
  • If key sorting or range navigation is needed — TreeMap.

Example:

Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 3);
hashMap.put("banana", 2);

Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("apple", 3);
treeMap.put("banana", 2);

System.out.println(hashMap); // Order is not guaranteed
System.out.println(treeMap); // Will output {apple=3, banana=2} in sorted order
What are the differences between the implementations… - sobes.tech