2.4.3 LinkedHashMap Explained
The LinkedHashMap
class in Java is a part of the Java Collections Framework and extends the HashMap
class. It maintains a doubly-linked list of the entries in the map, which preserves the insertion order of elements. This makes LinkedHashMap
suitable for scenarios where the order of elements is important.
Key Concepts
1. Insertion Order
Unlike HashMap
, which does not guarantee any order, LinkedHashMap
maintains the order in which elements are inserted. This means that when you iterate over a LinkedHashMap
, the elements will be returned in the order they were added.
Example
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put(3, "Cherry"); linkedHashMap.put(1, "Apple"); linkedHashMap.put(2, "Banana"); System.out.println(linkedHashMap); // Output: {3=Cherry, 1=Apple, 2=Banana}
2. Access Order
LinkedHashMap
can also be configured to maintain the order of elements based on access order. This means that the most recently accessed entry will be the last element in the iteration order. This feature is useful for implementing LRU (Least Recently Used) caches.
Example
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>(16, 0.75f, true); linkedHashMap.put(3, "Cherry"); linkedHashMap.put(1, "Apple"); linkedHashMap.put(2, "Banana"); linkedHashMap.get(3); // Accessing the element System.out.println(linkedHashMap); // Output: {1=Apple, 2=Banana, 3=Cherry}
3. Performance
LinkedHashMap
provides similar performance characteristics to HashMap
for basic operations like put
, get
, and remove
. The additional overhead of maintaining the linked list is minimal, making LinkedHashMap
efficient for most use cases.
Example
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put(1, "Apple"); linkedHashMap.put(2, "Banana"); linkedHashMap.put(3, "Cherry"); System.out.println(linkedHashMap.get(2)); // Output: Banana
4. Null Keys and Values
Like HashMap
, LinkedHashMap
allows one null
key and multiple null
values. This can be useful in scenarios where optional data needs to be stored.
Example
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put(null, "Null Key"); linkedHashMap.put(1, null); System.out.println(linkedHashMap); // Output: {null=Null Key, 1=null}
Examples and Analogies
Think of a LinkedHashMap
as a shopping list where items are added in the order you need them. When you go through the list, you see the items in the exact order you added them. If you mark an item as "used" (accessed), it moves to the end of the list, similar to how you might prioritize items in a to-do list.
By mastering LinkedHashMap
, you can efficiently manage and manipulate collections of data where the order of insertion or access is important, making your Java SE 11 applications more organized and performant.