Java Hashset.contains() produces mysterious result

后端 未结 3 917
忘了有多久
忘了有多久 2020-12-09 17:41

I don\'t usually code in Java, but recently I started not having a choice. I might have some major misunderstanding of how to properly use HashSet. So it might be possible s

3条回答
  •  囚心锁ツ
    2020-12-09 18:22

    Your equals method needs to take an Object.
    Because you declared it as taking an L, it becomes an additional overload instead of overriding the method.
    Therefore, when the hashSet class calls equals, it resolves to the base Object.equals method. When you call equals, you call your overload because a and b are both declared as L instead of Object.

    To prevent this issue in the future, you should add @Override whenever you override a method.
    This way, the compiler will warn you if it isn't actually an override.

提交回复
热议问题