javaandroidlisthashmapcontainskey

HashMap with byte array key and String value - containsKey() function doesn't work


I'm using a HashMap: byte[] key and String value. But I realize that even I put the same object (same byte array and same string value) by using

myList.put(TheSameByteArray, TheSameStringValue)

into HashMap, the table still inserts a new object with different HashMapEntry. Then function containsKey() cannot work.

Can someone explains this for me? How can I fix this? Thanks. (Android Java)

@Override public boolean containsKey(Object key) {
    if (key == null) {
        return entryForNullKey != null;
    }

    int hash = Collections.secondaryHash(key);
    HashMapEntry<K, V>[] tab = table;
    for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];
            e != null; e = e.next) {
        K eKey = e.key;
        if (eKey == key || (e.hash == hash && key.equals(eKey))) {
            return true;
        }
    }
    return false;
}

Solution

  • A byte[] (or any array) can't work properly as a key in a HashMap, since arrays don't override equals, so two arrays will be considered equal only if they refer to the same object.

    You'll have to wrap your byte[] in some custom class that overrides hashCode and equals, and use that custom class as the key to your HashMap.