在解決 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);
}
添加回答
舉報
0/150
提交
取消