在解決 hackerrank 上的問(wèn)題時(shí),我發(fā)現(xiàn)由于邏輯錯(cuò)誤,我的輸出與正確答案不同。我重現(xiàn)了邏輯錯(cuò)誤,以便以更好的方式解釋情況。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 的內(nèi)容相等,如何使 containsKey(b) 返回 true ?
1 回答

慕的地10843
TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
您不應(yīng)該使用數(shù)組作為 a 的鍵HashMap,因?yàn)閿?shù)組不會(huì)覆蓋equals和hashCode,因此包含完全相同元素的不同數(shù)組實(shí)例不會(huì)被 視為相同HashMap。
請(qǐng)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);
}
添加回答
舉報(bào)
0/150
提交
取消