具有字节数组键和字符串值的 HashMap - containsKey() 函数不起作用

HashMap with byte array key and String value - containsKey() function doesn#39;t work(具有字节数组键和字符串值的 HashMap - containsKey() 函数不起作用)
本文介绍了具有字节数组键和字符串值的 HashMap - containsKey() 函数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 HashMap: byte[] 键和字符串值.但我意识到,即使我使用

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)

到HashMap中,表还是会插入一个新的具有不同HashMapEntry的对象.那么函数 containsKey() 就不能工作了.

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

有人可以为我解释一下吗?我怎样才能解决这个问题?谢谢.(Android Java)

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;
}

推荐答案

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

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.

您必须将您的 byte[] 包装在一些覆盖 hashCodeequals 的自定义类中,并将该自定义类用作HashMap 的关键.

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() 函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)