在Java中实现equals方法 [英] Implementing the equals method in java

查看:65
本文介绍了在Java中实现equals方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我对Coor类的equals类的实现,该类仅包含2个整数x和y.这是实现此方法的正确方法吗?

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?

 public boolean equals(Object obj) {
        if (obj == null || obj.getClass() != this.getClass()) {
            return false;
        }
        Coor temp = (Coor) obj;
        if (temp.x == this.x && temp.y == this.y) {
            return true;
        } else {
            return false;
        }
    }

推荐答案

您可以再添加一项自反性检查(等于自我检查):

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;
}

这篇关于在Java中实现equals方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆