Implementing the equals method in java

前端 未结 7 942
醉酒成梦
醉酒成梦 2021-01-18 15:39

This is my implementation of the equals class for a Coor class which is just contains 2 ints x and y. would this be the proper way of implementing this method?



        
7条回答
  •  广开言路
    2021-01-18 15:53

    I believe this would work, at a quick glance. I say this because:

    1. It handles a null/improper types well.
    2. Performing x.equals(y) would yield the same result as y.equals(x).
    3. Performing x.equals(x) would return true.
    4. Performing x.equals(y) == true and y.equals(z) == true implies that x.equals(z) == true

    This question has certainly been asked many times before though. See here: Overriding equals and hashCode in Java. A book called Effective Java discusses this topic in great detail too, and the particular chapter is linked off of there.

提交回复
热议问题