简体   繁体   English

两个整数相等的方法

[英]Equals Method with two integers

I want to override the equals method. 我想重写equals方法。 But in my class are two integers. 但是在我的课上是两个整数。 I want to ask you if the equalsMethode is correct. 我想问你equalsMethode是否正确。

like this? 像这样?

thank you 谢谢

edit 1: my problem is, i want to remove an object of typ field of a 编辑1:我的问题是,我想删除一个类型字段的对象

Other than a couple of syntax errors, the implementation is not incorrect. 除了几个语法错误之外,实现也不是错误的。 However, the conversions to string are unnecessary: 但是,不需要转换为字符串:

return other.getRow() == getRow() && other.getColumn() == getColumn();

Other points: 其他要点:

  1. The if (this == obj) check is redundant. if (this == obj)检查是多余的。

  2. The if (getClass() != obj.getClass()) check may or may not be desirable, depending on whether you intend to ever subclass Field (I note that it is not declared final ). if (getClass() != obj.getClass())检查,取决于您是否打算对Field进行子类化(我注意到它没有声明为final )。

Last but not least, having overridden equals() , you should also override hashCode() . 最后但并非最不重要的一点是,在重写equals() ,您还应该重写hashCode() See What issues should be considered when overriding equals and hashCode in Java? 请参阅在Java中重写equals和hashCode时应考虑哪些问题? for a discussion. 进行讨论。

This is your equals method: 这是您的equals方法:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Field other = (Field) obj;
    if (column != other.column)
        return false;
    if (row != other.row)
        return false;
    return true;
}

and this is your hashCode mthod: 这是您的hashCode方法:

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + column;
        result = prime * result + row;
        return result;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM