Java 1.7 Override of hashCode() not behaving as I would expect

前端 未结 2 734
粉色の甜心
粉色の甜心 2021-01-19 14:52

I have a class where I have overridden both the hashCode method as well as the equals method. The equals method behaves as I would expect it to, however the hashCode method

2条回答
  •  一个人的身影
    2021-01-19 15:19

    The problem is not with .hashCode(); the problem is that you don't override .equals()!

    Look at your prototype:

    public boolean equals(Car car)
    

    Now have a look at the documentation for Object...

    What you should override is:

    public boolean equals(Object obj)
    

    Hence the error. You did implement hashCode correctly, however you use Object's .equals() implementation.

提交回复
热议问题