本文介绍了带有字节数组键和字符串值的HashMap - containsKey()函数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HashMap:byte []键和String值。但我意识到,即使我把相同的对象(相同的字节数组和相同的字符串值)通过使用

   > byte [] (或任何数组)不能作为 HashMap 中的键正常工作,因为数组不会覆盖 equals ,所以两个数组只有在引用同一个对象时才会被认为是相等的。



byte [] 在一些自定义类中覆盖 hashCode 和等于,并将该自定义类用作HashMap的关键字。


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;
}
解决方案

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.

这篇关于带有字节数组键和字符串值的HashMap - containsKey()函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!