亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

HashMap 的 containsKey 方法返回 false,但它的鍵是 integer[]

HashMap 的 containsKey 方法返回 false,但它的鍵是 integer[]

守候你守候我 2023-08-04 19:20:09
在解決 hackerrank 上的問題時,我發現由于邏輯錯誤,我的輸出與正確答案不同。我重現了邏輯錯誤,以便以更好的方式解釋情況。HashMap<Integer[] , Integer> hm = new HashMap<>();//both a and b have different hashcodeInteger[] a = {1, 1, 0, 0};Integer[] b = {1, 1, 0, 0}; hm.put(a,1);if (!hm.containsKey(b)) {    //key does not exists so, create new one      hm.put(b, 1);}else {    //key does exists so, put its value = value + 1    hm.put(b, hm.get(b)+1); }這里 hm.containsKey(b) 返回 false,但如果它返回 true,我的輸出將與正確的輸出匹配。由于 a 和 b 的內容相等,如何使 containsKey(b) 返回 true ?
查看完整描述

1 回答

?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

您不應該使用數組作為 a 的鍵HashMap,因為數組不會覆蓋equals和hashCode,因此包含完全相同元素的不同數組實例不會被 視為相同HashMap。


請List<Integer>改用鑰匙。


Map<List<Integer>, Integer> hm = new HashMap<>();


List<Integer> a = List.of(1, 1, 0, 0);

List<Integer> b = List.of(1, 1, 0, 0);


hm.put(a,1);


if (!hm.containsKey(b)) {

    //key does not exists so, create new one  

    hm.put(b, 1);

}

else {

    //key does exists so, put its value = value + 1

    hm.put(b, hm.get(b)+1); 

}


查看完整回答
反對 回復 2023-08-04
  • 1 回答
  • 0 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號