001/* 002 * BioJava development code 003 * 004 * This code may be freely distributed and modified under the 005 * terms of the GNU Lesser General Public Licence. This should 006 * be distributed with the code. If you do not have a copy, 007 * see: 008 * 009 * http://www.gnu.org/copyleft/lesser.html 010 * 011 * Copyright for this code is held jointly by the individual 012 * authors. These should be listed in @author doc comments. 013 * 014 * For more information on the BioJava project and its aims, 015 * or to join the biojava-l mailing list, visit the home page 016 * at: 017 * 018 * http://www.biojava.org/ 019 * 020 */ 021 022package org.biojava.utils.cache; 023 024import java.util.HashMap; 025import java.util.LinkedList; 026import java.util.Map; 027 028/** 029 * A cache that only remembers a given number of keys. 030 * 031 * @author Matthew Pocock 032 * @since 1.2 033 */ 034 035public class FixedSizeMap implements CacheMap { 036 private Map map = new HashMap(); 037 private LinkedList keys = new LinkedList(); 038 private int maxSize; 039 040 public int getMaxSize() { 041 return maxSize; 042 } 043 044 public FixedSizeMap(int maxSize) { 045 this.maxSize = maxSize; 046 } 047 048 public void put(Object key, Object value) { 049 if(map.containsKey(key)) { 050 keys.remove(key); 051 } 052 053 keys.addLast(key); 054 055 if(keys.size() > maxSize) { 056 Object k = keys.removeFirst(); 057 map.remove(k); 058 } 059 map.put(key, value); 060 061 } 062 063 public Object get(Object key) { 064 return map.get(key); 065 } 066 067 public void remove(Object key) { 068 map.remove(key); 069 keys.remove(key); 070 } 071}