执行equals()方法时出错

时间:2015-03-23 14:23:44

标签: java

我试图测试我的一个类,但是Eclipse正在向我指出一个错误的公共boolean equals(Object o)(给定另一个对象,它也是具有相同行和列值的Coord)尽管我'我试图测试另一种方法public boolean adjacent(Coord other)。因此,当我尝试执行adjcent(Coord other)方法时,它指向equals(Object o)方法的错误,特别是对于行 return this.equals(newValue);可以帮助我吗?

    import java.util.*;
    public class Mainnn {


        public static void main(String [] args)
        {
            Coord temp0 = new Coord(3,3);
            Coord temp = new Coord(2,3);
            System.out.println(temp);
            temp0.adjacent(temp);



        }
    }


public class Coord {

    public final int r;
    public final int c;


    public Coord(int r, int c)
    {
        this.r = r;
        this.c = c;
    }

    public Coord step(Direction d)
    {
        if(d == Direction.N)
        {
            Coord newValue = new Coord(r + 1, c);
            return newValue;
        }
        else if(d == Direction.S)
        {
            Coord newValue = new Coord(r - 1, c);
            return newValue;
        }
        else if(d == Direction.E)
        {
            Coord newValue = new Coord(r, c + 1);
            return newValue;
        }
        else if(d == Direction.W)
        {
            Coord newValue = new Coord(r, c - 1);
            return newValue;
        }

        else
            return this;

    }

    public Coord copy()
    {
        Coord clone = new Coord(r, c);
        return clone;

    }

    public boolean equals(Object o)
    {
        if(o instanceof Coord)
        {
            Coord newValue = (Coord)o;
            return this.equals(newValue);
        }
        else 
            return false;
    }

    public boolean adjacent(Coord other)
    {
        Coord temp1 = new Coord(r + 1, c);
        Coord temp2 = new Coord(r - 1, c);
        Coord temp3 = new Coord(r, c + 1);
        Coord temp4 = new Coord(r, c - 1);

        if(temp1.equals(other))
            return true;
        else if(temp2.equals(other))
            return true;
        else if(temp3.equals(other))
            return true;
        else if(temp4.equals(other))
            return true;
        else 
            return false;

    }

    public String toString()
    {
        return String.format("@(%d,%d)", r,c);
    }


}

1 个答案:

答案 0 :(得分:4)

你的equals方法似乎是递归的。它会调用自身并导致无限递归,从而导致堆栈溢出。

试试这个:

public boolean equals(Object o)
{
    if(o instanceof Coord)
    {
        Coord newValue = (Coord)o;
        return this.r == newValue.r && this.c == newValue.c;
    }
    else 
        return false;
}