Skip to content

Instantly share code, notes, and snippets.

@precious
Created December 8, 2011 23:54
Show Gist options
  • Save precious/1449324 to your computer and use it in GitHub Desktop.
Save precious/1449324 to your computer and use it in GitHub Desktop.
map of fixed size (removes eldest by access elements)
import java.util.LinkedHashMap;
import java.util.Map;
class FixedMap<K,V> extends LinkedHashMap<K,V> {
private int max_capacity;
public FixedMap(int initial_capacity, int max_capacity) {
super(initial_capacity, 0.75f, true);
this.max_capacity = max_capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size() > this.max_capacity;
}
}
public class FixedMapExample {
public static void main(String args[]) {
int maxCapacity = 10;
FixedMap fMap = new FixedMap(5,maxCapacity);
for(int i = 0;i < maxCapacity + 5;i++) {
fMap.put(i,i);
System.out.println("accessing fMap.get(0): " + fMap.get(0));
}
System.out.println("map with fixed size: " + fMap);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment