簡體   English   中英

如何使Java Hashtable.containsKey適用於Array?

[英]How do I make Java Hashtable.containsKey to work for Array?

很抱歉提出這個問題,但我是Java的新手。

Hashtable<byte[],byte[]> map = new Hashtable<byte[],byte[]>();
byte[] temp = {1, -1, 0};
map.put(temp, temp);
byte[] temp2 = {1, -1, 0};;
System.err.println(map.containsKey(temp2));

不適用於.containsKey(因為打印結果為“False”)

Hashtable<Integer,Integer> mapint = new Hashtable<Integer, Integer>();
int i = 5;
mapint.put(i, i);
int j = 5;
System.err.println(mapint.containsKey(j));

工作(打印結果為“True”)

我知道它與對象引用有關,但搜索后無法達到任何解決方案...

反正我是否可以使用Hashtable查找具有Array類型的鍵? 我只是想測試一個特定的數組是否在Hashtable中作為鍵...

任何點擊都會很棒。 謝謝!!!

你不能在HashTable/HashMap使用數組作為鍵,因為它們不會覆蓋Objectequals的默認實現,這意味着temp.equals(temp2)當且僅當temp==temp2 ,這不是真的在你的情況下。

對於鍵,可以使用Set<Byte>List<Byte>而不是byte[]

例如 :

Hashtable<List<Byte>,Byte[]> map = new Hashtable<List<Byte>,Byte[]>();
Byte[] temp = {1, -1, 0};
map.put(Arrays.asList(temp), temp);
Byte[] temp2 = {1, -1, 0};;
System.err.println(map.containsKey(Arrays.asList(temp2)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM