在解决有关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?
答案 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>
);
};
的键,因为数组不会覆盖HashMap
和equals
,所以包含完全相同元素的不同数组实例是hashCode
认为不完全相同。
请改用HashMap
键。
List<Integer>