[英]Error while performing equals() method
我正在嘗試測試我的一個類,但是Eclipse一直在向我指出一個指向公共boolean equals(Object o)
的錯誤(給另一個對象,它也是具有相同行和列值的Coord),盡管我正在嘗試測試另一種方法是public boolean adjacent(Coord other)
。 因此,當我嘗試執行adjcent(Coord other)
方法時,它使我指向equals(Object o)
方法的錯誤,尤其是該行
return this.equals(newValue);
smb可以幫我嗎?
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);
}
}
您的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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.