Last active
August 29, 2015 14:06
-
-
Save ypetya/f226c479cf85424c720c to your computer and use it in GitHub Desktop.
WeakValueHashMapFrom http://stackoverflow.com/questions/13889051/weak-hashmap-with-weak-references-to-the-values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package tools.cache; | |
| import java.lang.ref.WeakReference; | |
| import java.util.HashMap; | |
| import java.util.Iterator; | |
| import java.util.Map; | |
| public class WeakValueHashMap<K,V> extends HashMap<K,V> implements Map<K, V> { | |
| private HashMap<K,WeakReference<V>> mDatabase=new HashMap<K, WeakReference<V>>(); | |
| @Override | |
| public V get(Object key) { | |
| WeakReference<V> weakRef=mDatabase.get(key); | |
| if(weakRef!=null) { | |
| return weakRef.get(); | |
| } | |
| this.mDatabase.remove(key); | |
| return null; | |
| } | |
| @Override | |
| public V put(K key, V value) { | |
| WeakReference<V> weak = new WeakReference<V>(value); | |
| mDatabase.put(key, weak); | |
| return value; | |
| } | |
| public void removeInvalidKeyPairs() { | |
| Iterator<Entry<K,WeakReference<V>>> it = mDatabase.entrySet().iterator(); | |
| while(it.hasNext()) { | |
| Entry<K,WeakReference<V>> e = it.next(); | |
| if(e.getValue()==null) { | |
| it.remove(); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment