我有一个任务要实现一个通用的 Pair 接口(interface),它表示像 (x,y) 这样的有序对。我正在尝试编写 equals 方法,但我必须使参数成为一般对象而不是一对,所以我不知道如何获取它的坐标。当我尝试编译时出现未找到符号错误,因为 Object 类没有 fst 和 snd 方法。我应该抛出异常还是什么?注意:我的教授给了我们一个模板,我只是在填写方法,我不认为我可以更改参数或方法。
相关代码如下:
public class Pair<T1,T2> implements PairInterface<T1,T2>
{
private T1 x;
private T2 y;
public Pair(T1 aFirst, T2 aSecond)
{
x = aFirst;
y = aSecond;
}
/**
* Gets the first element of this pair.
* @return the first element of this pair.
*/
public T1 fst()
{
return x;
}
/**
* Gets the second element of this pair.
* @return the second element of this pair.
*/
public T2 snd()
{
return y;
}
...
/**
* Checks whether two pairs are equal. Note that the pair
* (a,b) is equal to the pair (x,y) if and only if a is
* equal to x and b is equal to y.
* @return true if this pair is equal to aPair. Otherwise
* return false.
*/
public boolean equals(Object otherObject)
{
if(otherObject == null)
{
return false;
}
if(getClass() != otherObject.getClass())
{
return false;
}
T1 a = otherObject.fst();
T2 b = otherObject.snd();
if (x.equals(a) && y.equals(b))
{
return true;
}
else
{
return false;
}
}
这些是我得到的错误:
./Pair.java:66: cannot find symbol
symbol : method fst()
location: class java.lang.Object
T1 a = otherObject.fst();
^
./Pair.java:67: cannot find symbol
symbol : method snd()
location: class java.lang.Object
T2 b = otherObject.snd();
^
最佳答案
equals
方法的参数是一个Object
,它不保证有你的方法fst
或snd
,因此编译器错误。为了能够调用这些方法,您需要有一个 Pair
对象。
测试传入对象的类是标准做法,看它是否与this
是同一个类,如果不是同一个类则返回false
.通常这是通过 instanceof
完成的,如果 true
紧随其后。强制转换允许编译器将对象视为您所说的类。这允许编译器找到您要调用的方法。
if(otherObject == null)
{
return false;
}
// Use instanceof
if(!(otherObject instanceof Pair))
{
return false;
}
// Cast - use <?, ?>; we don't know what they are.
Pair<?, ?> otherPair = (Pair<?, ?>) otherObject;
Object a = otherPair.fst();
Object b = otherPair.snd();
// Simplified return
return (x.equals(a) && y.equals(b));
关于java - 不能使用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34933548/