package net.x4a42.volksempfaenger.data;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

public class CacheMap<K, V> {

	private Map<K, SoftReference<V>> map;

	public CacheMap(int initialCapacity, float loadFactor) {
		map = new HashMap<K, SoftReference<V>>(initialCapacity, loadFactor);
	}

	public CacheMap(int initialCapacity) {
		this(initialCapacity, 0.75f);
	}

	public CacheMap() {
		this(16);
	}

	public void clear() {
		map.clear();
	}

	public boolean containsKey(Object key) {
		if (map.containsKey(key)) {
			V value = map.get(key).get();
			if (value != null) {
				return true;
			} else {
				map.remove(key);
				return false;
			}
		} else {
			return false;
		}
	}

	public V get(Object key) {
		SoftReference<V> valueRef = map.get(key);
		if (valueRef != null) {
			V value = valueRef.get();
			if (value == null) {
				map.remove(key);
			}
			return value;
		} else {
			return null;
		}
	}

	public boolean isEmpty() {
		return map.isEmpty();
	}

	public void put(K key, V value) {
		map.put(key, new SoftReference<V>(value));
	}

	public V remove(Object key) {
		SoftReference<V> valueRef = map.remove(key);
		if (valueRef != null) {
			return valueRef.get();
		} else {
			return null;
		}
	}

	public int size() {
		return map.size();
	}

}

@@ -482,246 +482,8 @@
 %09%7D%0A%0A
-%09public boolean containsKey(Object key) %7B%0A%09%09if (map.containsKey(key)) %7B%0A%09%09%09V value = map.get(key).get();%0A%09%09%09if (value != null) %7B%0A%09%09%09%09return true;%0A%09%09%09%7D else %7B%0A%09%09%09%09map.remove(key);%0A%09%09%09%09return false;%0A%09%09%09%7D%0A%09%09%7D else %7B%0A%09%09%09return false;%0A%09%09%7D%0A%09%7D%0A%0A
 %09pub

Remove containsKey() because of possible race conditions