CGB-301-Cache缓存Fifo算法Demo

目录

  • 一. 实现一个简单的SimpleCache

一. 实现一个简单的SimpleCache

基于 HashMap和LinkedList的Cache的小Demo

package com.company.oopfeatures;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * 
 * @author apple
 * @email [email protected]
 * 创建时间: 2019年9月25日 下午2:52:42
 */
public class Test03SimpleFifoCache {
	public static void main(String[] args) {
		SimpleFifoCache cache = new SimpleFifoCache(3);
		cache.putObject(1, "A");
		cache.putObject(2, "B");
		cache.putObject(3, "C");
		System.out.println(cache);
		cache.putObject(4, "D");
		cache.putObject(5, "D");
		cache.putObject(6, "D");
		System.out.println(cache);
	}
}

/**
 * 存入元素 A/B/C/D 当存入D的时候A被删除
 * 实现FIFO算法
 * @author apple
 *
 */
class SimpleFifoCache {
	private int maxSize; // 集合的最大容量
	private Map<Object, Object> cacheMap = new HashMap<>();
	private Deque<Object> keyOrders = new LinkedList<Object>();

	public SimpleFifoCache(int maxSize) {
		this.maxSize = maxSize;
	}

	public Object getObject(Object key) {
		if (keyOrders.contains(key)) {
			return cacheMap.get(key);
		}
		return null;
	}

	public void putObject(Object key, Object value) {
		keyOrders.add(key);
		System.out.println("keyOrders===>" + keyOrders);
		cacheMap.put(key, value);
		if (cacheMap.size() > maxSize) {
			Object firstKey = keyOrders.pop();
			cacheMap.remove(firstKey);
		}
	}

	@Override
	public String toString() {
		return cacheMap.toString();
	}

}

你可能感兴趣的:(CGB-301-Cache缓存Fifo算法Demo)