相关疑难解决方法(0)

为什么我需要覆盖Java中的equals和hashCode方法?

最近我读了这个 Developer Works文档.

该文档是关于定义hashCode()equals()有效和正确的,但我无法弄清楚为什么我们需要覆盖这两种方法.

如何有效地实施这些方法?

java equals hashcode

355
推荐指数
15
解决办法
39万
查看次数

如何在Java中重写equals方法

我试图在Java中重写equals方法.我有一个类People,基本上有2个数据域nameage.现在我想覆盖equals方法,以便我可以检查2个People对象.

我的代码如下

public boolean equals(People other){
    boolean result;
    if((other == null) || (getClass() != other.getClass())){
        result = false;
    } // end if
    else{
        People otherPeople = (People)other;
        result = name.equals(other.name) &&  age.equals(other.age);
    } // end else

    return result;
} // end equals
Run Code Online (Sandbox Code Playgroud)

但是当我写age.equals(other.age)它给我错误时,equals方法只能比较String和age是Integer.

==建议使用运算符,我的问题解决了.

java overriding equals

100
推荐指数
7
解决办法
21万
查看次数

使用equals方法比较两个对象,Java

我有一个对象数组,我想与目标对象进行比较.我想返回与目标对象完全匹配的对象数.

这是我的计数方法:

public int countMatchingGhosts(Ghost target) {
        int count=0;
        for (int i=0;i<ghosts.length;i++){
            if (ghosts[i].equals(target));
            count++;
        }
        return count;
Run Code Online (Sandbox Code Playgroud)

这是我的平等方法:

public boolean equals(Ghost other){
           if(this == other) return true;
           if( !(other instanceof Ghost) ) return false;
           Ghost p = (Ghost)other;

        if (this.x == p.x && this.y == p.y && this.direction==p.direction && this.color.equals(p.color))
            return true;
        else
            return false;
Run Code Online (Sandbox Code Playgroud)

我运行了一些测试代码,我希望只有1个匹配,但我得到3个.你看到有什么错误吗?

java arrays if-statement equals object

4
推荐指数
1
解决办法
8454
查看次数

标签 统计

equals ×3

java ×3

arrays ×1

hashcode ×1

if-statement ×1

object ×1

overriding ×1