joshua
joshua

Reputation: 67

Error while performing equals() method

Im trying to test one of my classes but Eclipse is keeping pointing me with an error towards public boolean equals(Object o)(Given another object, is it also a Coord with the same row and column values) though I'm trying to test another method which is public boolean adjacent(Coord other). So, when I try to perform adjcent(Coord other) method it points me to the error to the equals(Object o) method, in particular to the line
return this.equals(newValue); Can smb help me with that?

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


}

Upvotes: 0

Views: 87

Answers (1)

juhist
juhist

Reputation: 4314

Your equals method seems to be recursive. It will call itself and result in an infinite recursion, causing a stack overflow.

Try this:

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

Upvotes: 4

Related Questions