我正在尝试实现自己的LRU缓存。是的,我知道Java提供了LinkedHashMap来实现这个目的,但我正在尝试使用基本数据结构来实现它。
从阅读有关此主题的资料中,我了解到需要一个HashMap来进行O(1)键查找和一个链表来管理“最近最少使用”驱逐策略。我找到了这些参考资料,它们都使用标准库哈希映射表,但实现了自己的链表:
中译英:
这导致了三个问题:
问题1:当我使用存储在HashMap中的迭代器更新LinkedList时,我会收到ConcurrentModificationException异常。
问题2:如何检索ListIterator指向的值?似乎我只能检索next()值。
问题3:是否有办法使用Java集合LinkedList实现这个LRU缓存,还是我真的必须实现自己的链接列表?
从阅读有关此主题的资料中,我了解到需要一个HashMap来进行O(1)键查找和一个链表来管理“最近最少使用”驱逐策略。我找到了这些参考资料,它们都使用标准库哈希映射表,但实现了自己的链表:
中译英:
- "LRU缓存和快速定位对象通常使用哪些数据结构?" (stackoverflow.com)
- "实现LRU缓存的最佳方式是什么?" (quora.com)
- "在C++中实现LRU缓存" (uml.edu)
- "LRU缓存(Java)" (programcreek.com)
哈希表应直接存储如下所示的链表节点。我的缓存应存储整数键和字符串值。
然而,在Java中,LinkedList集合不会暴露其内部节点,因此我无法将它们存储在HashMap中。我可以将HashMap存储为LinkedList中的索引,但是获取项目需要O(N)时间。因此,我尝试存储ListIterator。import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
public class LRUCache {
private static final int DEFAULT_MAX_CAPACITY = 10;
protected Map<Integer, ListIterator> _map = new HashMap<Integer, ListIterator>();
protected LinkedList<String> _list = new LinkedList<String>();
protected int _size = 0;
protected int _maxCapacity = 0;
public LRUCache(int maxCapacity) {
_maxCapacity = maxCapacity;
}
// Put the key, value pair into the LRU cache.
// The value is placed at the head of the linked list.
public void put(int key, String value) {
// Check to see if the key is already in the cache.
ListIterator iter = _map.get(key);
if (iter != null) {
// Key already exists, so remove it from the list.
iter.remove(); // Problem 1: ConcurrentModificationException!
}
// Add the new value to the front of the list.
_list.addFirst(value);
_map.put(key, _list.listIterator(0));
_size++;
// Check if we have exceeded the capacity.
if (_size > _maxCapacity) {
// Remove the least recently used item from the tail of the list.
_list.removeLast();
}
}
// Get the value associated with the key.
// Move value to the head of the linked list.
public String get(int key) {
String result = null;
ListIterator iter = _map.get(key);
if (iter != null) {
//result = iter
// Problem 2: HOW DO I GET THE STRING FROM THE ITERATOR?
}
return result;
}
public static void main(String argv[]) throws Exception {
LRUCache lruCache = new LRUCache(10);
lruCache.put(10, "This");
lruCache.put(20, "is");
lruCache.put(30, "a");
lruCache.put(40, "test");
lruCache.put(30, "some"); // Causes ConcurrentModificationException
}
}
这导致了三个问题:
问题1:当我使用存储在HashMap中的迭代器更新LinkedList时,我会收到ConcurrentModificationException异常。
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:953)
at java.util.LinkedList$ListItr.remove(LinkedList.java:919)
at LRUCache.put(LRUCache.java:31)
at LRUCache.main(LRUCache.java:71)
问题2:如何检索ListIterator指向的值?似乎我只能检索next()值。
问题3:是否有办法使用Java集合LinkedList实现这个LRU缓存,还是我真的必须实现自己的链接列表?