Junior — Middle
Can you explain what a LinkedHashMap in Java is and what features it has?
sobes.tech AI
Answer from AI
LinkedHashMap in Java is an implementation of the Map interface that maintains the order of insertion of elements.
Features of LinkedHashMap:
- Elements are stored as key-value pairs, like in HashMap.
- Unlike HashMap, LinkedHashMap maintains a linked list of the entries, which allows iteration in the order of insertion.
- It supports access order, which is useful for implementing caches with LRU (least recently used) policy.
- Access, insertion, and removal times are approximately O(1), similar to HashMap.
Example usage:
import java.util.LinkedHashMap;
public class Example {
public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
// Iteration in insertion order
for (Integer key : map.keySet()) {
System.out.println(key + " -> " + map.get(key));
}
}
}
The output will be in the order 1, 2, 3, which is not guaranteed in a regular HashMap.