Senior
What is the difference between HashMap and LinkedHashMap?
sobes.tech AI
Answer from AI
Main differences between HashMap and LinkedHashMap:
-
Order of elements:
HashMapdoes not guarantee the order of elements during iteration.LinkedHashMapmaintains the insertion order of elements (or access order if access-order is enabled).
-
Performance:
HashMapis slightly faster due to the absence of an additional structure for order.LinkedHashMapis slightly slower because it supports a linked list for order.
-
Usage:
HashMapis suitable when order does not matter.LinkedHashMapis convenient when a predictable iteration order is needed, such as for caches.
Example of using LinkedHashMap for a cache with removal of old elements:
LinkedHashMap<K, V> cache = new LinkedHashMap<K, V>(initialCapacity, loadFactor, true) {
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > MAX_ENTRIES;
}
};