Implementing the equals method in java

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

    You could add one more check for reflexive equality (equal to self):

     public boolean equals(Object obj) {
    
        // Reflexive equality: did I get passed myself?
        if(this == obj){
            return true;
        }
    
        if (obj == null || obj.getClass() != this.getClass()) {
            return false;
        }
    
        Coor temp = (Coor) obj;
        return temp.x == this.x && temp.y == this.y;
    }
    

提交回复
热议问题