I want to store some data in WeakHashMap, but there is a problem. Say we have a code:
public class WeakMapTest {
public static void main(String[] args) {
WeakHashMap<Object, Object> map = new WeakHashMap<Object, Object>();
map.put(null, 0);
map.put(new Integer(1), null);
map.put(new Integer(2), 2);
System.out.println(map.get(new Integer(2)));
System.gc(); //assume this call made implicitly by JVM
if (map.containsKey(new Integer(2))) {
System.out.println(map.get(new Integer(2)));
} else {
System.out.println("Key is deleted");
}
}
}
Output will be
2
Key is deleted
which is logical.
But there is another case:
if (map.containsKey(new Integer(2))) {
System.gc(); //assume this call made implicitly by JVM
System.out.println(map.get(new Integer(2)));
} else {
System.out.println("Key is deleted");
}
and the results is not as good:
2
null
How can I avoid such misleading results? Bare in mind that values and keys can be null.