問題描述
我正在使用 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的對象.那么函數(shù) 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[]
(或任何數(shù)組)不能作為 HashMap
,因為數(shù)組不會覆蓋equals
,所以兩個數(shù)組只有在引用同一個對象時才會被認為是相等的.
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[]
包裝在一些覆蓋 hashCode
和 equals
的自定義類中,并將該自定義類用作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.
這篇關于具有字節(jié)數(shù)組鍵和字符串值的 HashMap - containsKey() 函數(shù)不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!