Sobes.tech
Junior — Middle

What is the difference between HashMap and LinkedHashMap data structures in Java?

sobes.tech AI

Answer from AI

HashMap and LinkedHashMap are implementations of the Map interface in Java, but they have a key difference in the order of element storage:

  • HashMap does not guarantee the order of elements. Key-value pairs are stored without a specific order, which may change when adding or removing elements.

  • LinkedHashMap maintains the insertion order of elements. This is achieved by using a linked list that preserves the order of key insertion. LinkedHashMap can also be configured for access order, which is useful, for example, for implementing caches.

Example:

Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("one", 1);
hashMap.put("two", 2);
hashMap.put("three", 3);

Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("one", 1);
linkedHashMap.put("two", 2);
linkedHashMap.put("three", 3);

System.out.println(hashMap.keySet());       // Order may be arbitrary
System.out.println(linkedHashMap.keySet()); // Order: [one, two, three]

Thus, if the order of elements is important, it is recommended to use LinkedHashMap.