HashMap key problems

Posted by Peterdk on Stack Overflow See other posts from Stack Overflow or by Peterdk
Published on 2010-06-12T16:42:24Z Indexed on 2010/06/12 16:52 UTC
Read the original article Hit count: 402

Filed under:
|
|

I'm profiling some old java code and it appears that my caching of values using a static HashMap and a access method does not work.

Caching code (a bit abstracted):

static HashMap<Key, Value> cache = new HashMap<Key, Value>();

public static Value getValue(Key key){
    System.out.println("cache size="+ cache.size());                
    if (cache.containsKey(key)) {
        System.out.println("cache hit");
        return cache.get(key);
    } else {
        System.out.println("no cache hit");
        Value value = calcValue();
        cache.put(key, value);
        return value;
    }
}

Profiling code:

for (int i = 0; i < 100; i++)
{ 
    getValue(new Key());
}

Result output:

 cache size=0
 no cache hit
 (..)
 cache size=99
 no cache hit

It looked like a standard error in Key's hashing code or equals code. However:

 new Key().hashcode == new Key().hashcode // TRUE
 new Key().equals(new Key()) // TRUE

What's especially weird is that cache.put(key, value) just adds another value to the hashmap, instead of replacing the current one.

So, I don't really get what's going on here. Am I doing something wrong?

© Stack Overflow or respective owner

Related posts about java

Related posts about key