Implementing the equals method in java

前端 未结 7 926
醉酒成梦
醉酒成梦 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:55

    Seems ok. For brevity sake, you can do:

    return temp.x == this.x && temp.y == this.y
    

    Instead of

    if (temp.x == this.x && temp.y == this.y) {
            return true;
        } else {
            return false;
        }
    

    Also, please keep in mind the Object Contract (seriously!).

    See the accepted answer here: What issues should be considered when overriding equals and hashCode in Java?

    This can save you a huge about of headache in the future.

提交回复
热议问题