尽管HashMap的containsKey方法返回false,但HashMap的键为integer []类型?

时间:2019-09-18 17:59:18

标签: java hashmap hashcode

在解决有关hackerrank的问题时,我发现我的输出由于逻辑错误而与正确答案不同。我已经重新创建了逻辑错误,以更好地解释这种情况。

HashMap<Integer[] , Integer> hm = new HashMap<>();

//both a and b have different hashcode
Integer[] 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 个答案:

答案 0 :(得分:4)

您不应该将数组用作const AddSlider = ({setState, state, steps}) => { const viewRef = useRef(null); console.log('On render', viewRef.current); // prints after every re-render // viewRef.current is not null after a render is triggered in the component const tapSliderGesture = (locationX) => { console.log(viewRef.current); // on iOS this prints the ref object // on Android it prints null viewRef.current.measure((fx, fy, width, height, px) => { const location = Math.round(((locationX - px) / width) * steps); if (location !== state) { setState(location); } }); }; return ( <View ref={ viewRef } onResponderMove={ (evt) => { tapSliderGesture(evt.nativeEvent.locationX); } } onResponderGrant={ (evt) => { tapSliderGesture(evt.nativeEvent.locationX); } } > <Slider .../> </View> ); }; 的键,因为数组不会覆盖HashMapequals,所以包含完全相同元素的不同数组实例是hashCode认为不完全相同。

请改用HashMap键。

List<Integer>