LRUCache
最近访问的放到链表的末尾,访问最少的在链表的头部,当新增元素时,size()>cacheSize则移除链表头部的元素。
package com.my.test.contain;
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache extends LinkedHashMap<String,String>
{
/**
* serialVersionUID
*/
private static final long serialVersionUID = -825328968456387095L;
private int cacheSize;
public LRUCache(int cacheSize) {
// 初始化容量为cacheSize/0.75 + 1
super((int)Math.ceil(cacheSize / 0.75) + 1, 0.75f, true);
this.cacheSize = cacheSize;
}
// map中的数据量大于指定的缓存数量 就自动删除最老的数据
@Override
protected boolean removeEldestEntry(Map.Entry<String,String> eldest) {
return this.size() > cacheSize;
}
public static void main(String args[]) {
LRUCache lruCache = new LRUCache(3);
lruCache.put("1", "a");
lruCache.put("2", "b");
lruCache.put("3", "c");
lruCache.put("4", "d");
System.out.println(lruCache.get("1"));
System.out.println(lruCache.get("2"));
lruCache.put("5", "e");
System.out.println(lruCache);
}
}
输出:
null
b
{4=d, 2=b, 5=e}
MinHeap
使用PriorityQueue构建,可指定初始容量,容量不足时自动扩容。若希望保持最初的容量不变,需要在添加元素时,判断size()是否大于最初的容量,如果大于则弹出元素。
package com.my.test.contain;
import java.util.PriorityQueue;
public class MinHeap extends PriorityQueue<Integer>
{
/**
* serialVersionUID
*/
private static final long serialVersionUID = -809886845293263611L;
public MinHeap(int heapSize) {
super(heapSize);
}
public static void main(String args[]) {
MinHeap minHeap = new MinHeap(3);
minHeap.offer(2);
minHeap.offer(1);
minHeap.offer(3);
System.out.println(minHeap.peek());
System.out.println(minHeap.poll());
System.out.println(minHeap.poll());
System.out.println(minHeap.poll());
System.out.println(minHeap.poll());
}
}
输出:
1
1
2
3
null
MaxHeap
使用PriorityQueue构建,可指定初始容量及比较规则,容量不足时自动扩容,若希望保持最初的容量不变,需要在添加元素时,判断size()是否大于最初的容量,如果大于则弹出元素。
package com.my.test.contain;
import java.util.PriorityQueue;
public class MaxHeap extends PriorityQueue<Integer>
{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 8209174800167281392L;
public MaxHeap(int heapSize) {
super(heapSize, (o1, o2)->{return o2 - o1;});
}
public static void main(String args[]) {
MaxHeap maxHeap = new MaxHeap(3);
maxHeap.offer(2);
maxHeap.offer(1);
maxHeap.offer(3);
System.out.println(maxHeap.peek());
System.out.println(maxHeap.size());
System.out.println(maxHeap.poll());
System.out.println(maxHeap.poll());
System.out.println(maxHeap.poll());
System.out.println(maxHeap.poll());
}
}
输出:
3
3
3
2
1
null