记录一次坑。
有2个hashmap:
HashMap<Character, Integer> window = new HashMap<>();
HashMap<Character, Integer> need = new HashMap<>();
我比较他们里面的value数据时用了:
window.get(c) == need.get(c)
导致某些用例无法通过,原因在于直接赋值的Integer对象在-128到127范围内时会被缓存,故而:
Integer a = 127;
Integer b = 127;
return a == b
是返回True的,而:
Integer a = 128
Integer b = 128
return a == b
会返回False,因为超过缓存的范围,就会直接new对象,导致有些用例会通过,而有些用例无法通过。所以Integer比较最好使用:
a.equals(b)
博客内容讲述了在Java编程中,使用HashMap存储Integer对象时,由于Integer对象的缓存机制,直接使用`==`进行比较可能会导致不一致的结果。当Integer值在-128到127之间时,它们会被缓存并复用,导致相等判断返回True。超出这个范围的Integer对象则每次都会新建,`==`比较会返回False。因此,建议在比较Integer时使用`.equals()`方法以确保正确性。
7137

被折叠的 条评论
为什么被折叠?



