pda/zhuike/.svn/pristine/c8/c877dea0107082d557c2118d382...

84 lines
1.8 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.novelbook.android.utils;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 按照插入顺序排序的Map当超出容量时将最早插入的对象移除。
*
* @param <K>
* @param <V>
*/
public class FIFOMap<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 27034646516234314L;
protected int maxSize;
public FIFOMap(int maxSize) {
super(maxSize, 0.75f, false);
this.maxSize = maxSize;
}
@Override
protected boolean removeEldestEntry(Entry<K, V> eldest) {
return maxSize < size();
}
@Override
public synchronized V put(K key, V value) {
return super.put(key, value);
}
@Override
public synchronized void putAll(Map<? extends K, ? extends V> m) {
super.putAll(m);
}
@Override
public synchronized V remove(Object key) {
return super.remove(key);
}
public void setCapacity(int size) {
maxSize = size;
}
public int getCapacity() {
return maxSize;
}
public static void main(String[] args) {
int maxSize = 100;
FIFOMap<Integer, Integer> map = new FIFOMap<Integer, Integer>(maxSize);
for (int i = 1; i <= maxSize; i++) {
map.put(i, i);
assertTrue(map.size() == i);
}
for (int i = 1; i <= maxSize; i++) {
map.put(i, i);
assertTrue(map.size() == maxSize);
}
for (int i = 101; i <= 100 + maxSize; i++) {
map.put(i, i);
assertTrue(map.size() == maxSize);
}
for (int i = 191; i <= 100 + maxSize; i++) {
map.remove(i);
assertTrue(map.size()== maxSize + 190 - i );
}
for (int i = 101; i <= 100 + maxSize; i++) {
map.put(i, i);
}
for (int i = 1; i <= 10000 + maxSize; i++) {
map.put(i, i);
}
assertTrue(map.size() == maxSize);
}
private static void assertTrue(boolean flag) {
if ( !flag ) System.out.println("should be true. but is false.");
}
}