我有一個任務來實現一個通用的Pair接口,它代表像(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();
^
在https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html中閱讀有關投射的部分。坦率地說,我很驚訝你的老師讓你使用泛型,如果你還不知道如何施放,這是一件非常複雜的事情。而且,如果你使用'first'和'second'而不是'fst'和'snd',你的代碼將會非常可讀。 –
一旦建立實際的對象類型,您將需要執行顯式轉換。 –
你必須將另一個物體成爲一對,第一個'對, ?> otherPair =(對, ?>)otherObject;'。 – EpicPandaForce