Junior — Middle
How does the behavior and features of HashMap differ from LinkedHashMap in Java?
sobes.tech AI
Answer from AI
HashMap and LinkedHashMap in Java differ as follows:
-
HashMap stores key-value pairs without any guarantee of order. The order of elements may change when adding or removing entries.
-
LinkedHashMap extends HashMap and maintains the insertion order of elements. This means that when iterating, elements will be returned in the order they were added.
Features:
- LinkedHashMap is slightly slower due to maintaining a linked list for order.
- LinkedHashMap can be used to implement caches with removal based on access order.
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: " + hashMap.keySet());
System.out.println("LinkedHashMap: " + linkedHashMap.keySet());
Output:
HashMap: [two, one, three]
LinkedHashMap: [one, two, three]
Thus, if the order of elements is important, it is recommended to use LinkedHashMap.