lrucache.java

来自「WordNet is an extensive database develop」· Java 代码 · 共 56 行

JAVA
56
字号
/*
 * LRUCache utility class
 *
 * Copyright 1998 by Oliver Steele.  You can use this software freely so long as you preserve
 * the copyright notice and this restriction, and label your changes.
 */
package edu.gwu.wordnet.util;
import java.util.*;

/** A fixed-capacity <code>Cache</code> that stores the <var>n</var> most recently used
 * keys.
 *
 * @author Oliver Steele, steele@cs.brandeis.edu
 * @version 1.0
 */
public class LRUCache implements Cache {
	protected int capacity;
	protected Vector keys;
	protected Hashtable map;
	
	public LRUCache(int capacity) {
		this.capacity = capacity;
		keys = new Vector(capacity);
		map = new Hashtable(capacity);
	}
	
	public synchronized void put(Object key, Object value) {
		remove(key);
		keys.insertElementAt(key, 0);
		map.put(key, value);
		if (keys.size() >= capacity) {
			remove(keys.elementAt(keys.size() - 1));
		}
	}
	
	public synchronized Object get(Object key) {
		Object value = map.get(key);
		if (value != null) {
			keys.removeElement(key);
			keys.insertElementAt(key, 0);
		}
		return value;
	}
	
	public synchronized void remove(Object key) {
		if (map.remove(key) != null) {
			keys.removeElement(key);
			--capacity;
		}
	}
	
	public synchronized void clear() {
		keys.removeAllElements();
		map.clear();
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?