سؤال

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.

هل كانت مفيدة؟

المحلول

Find my the solution while I was writing this question, so just decided to share.

Object value = map.get(new Integer(2));
if (map.containsKey(new Integer(2))) {
    System.gc(); // can happen here
    System.out.println(value);
} else {
    System.out.println("Key is deleted");
}

I have to get value first and only then check for key existence. That way I am protected against incorrect result. Current result is:

2
2

that is correct, at least for my case.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top