Queue implementation by Map.Entry <K, V>
I'm doing my homework. I need a <key, value> data structure to store the cache. I also need my structure to delete the oldest element when there is no room for a new element (analogue of LinkedHashMap.removeEldestEntry() ).
I want to implement a queue on Map.Entry<K, V> for assignment. Is this the correct solution to the problem?
Explanation:
public class Queue<K, V> { protected LinkedList<MyEntry<K, V>> list; public Queue() { list = new LinkedList<MyEntry<K,V>>(); } //// } final class MyEntry<K, V> implements Map.Entry<K, V> { private final K key; private V value; public MyEntry(K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { V old = this.value; this.value = value; return old; } } And then:
Queue<String, String> queue = new Queue<String>(); +4
1 answer
If you use LinkedHashMap, than the first element on the map that you move with the iterator, since LinkedHashMap keeps the order of the pairs in the same order in which you enter them. note that if you are extracting an object from the map, you need to delete and add it again to preserve the order of the pairs in the associated HashMap
+1