我正在研究Java中的抽象數據類型對。它應該有兩個對象,並將它們組合在一起。這應該不到30分鐘,但我一直在這裏工作了3個半小時。我相信我有正確的前兩種方法,但我無法弄清楚逆向或平等。你可以看到我試圖在代碼是什麼:試圖創建一個將兩個對象配對的ADT
public class Pair<T1,T2> implements PairInterface<T1,T2>
{
// TO DO: Your instance variables here.
public T1 first;
public T2 second;
public Pair(T1 aFirst, T2 aSecond)
{
first = aFirst;
second = aSecond;
}
/* Gets the first element of this pair.
* @return the first element of this pair.
*/
public T1 fst()
{
return this.first;
}
/* Gets the second element of this pair.
* @return the second element of this pair.
*/
public T2 snd()
{
return this.second;
}
/* Gets a NEW pair the represents the reversed order
* of this pair. For example, the reverse order of the
* pair (x,y) is (y,x).
* @return a NEW pair in reverse order
*/
public PairInterface<T2,T1> reverse()
{
return PairInterface<this.snd(),this.fst()>;//Pair<second;first>
}
/* 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.
*
* Note that if you forget to implement this method, your
* compiler will not complain since your class inherits this
* method from the class Object.
*
* @param otherObject the object to be compared to this object.
* @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;
}
if (otherObject.fst.equals(this.fst) &&
otherObject.snd.equals(this.snd))
{
return true;
} else {
return false;
}
}
/* Generates a string representing this pair. Note that
* the String representing the pair (x,y) is "(x,y)". There
* is no whitespace unless x or y or both contain whitespace
* themselves.
*
* Note that if you forget to implement this method, your
* compiler will not complain since your class inherits this
* method from the class Object.
*
* @return a string representing this pair.
*/
public String toString()
{
return "("+first.toString()+","+second.toString()+")";
}
}
你是什麼意思由_「無法找出相反或等於」_?請詳細解釋。另外,請閱讀[FAQ]和[Ask]。你寫的問題聽起來很像「請爲我做的工作」。 – 2014-09-10 15:42:08
那麼,我會從平等開始。我假設它用於確定另一對是否等於這一對,那麼爲什麼它需要一個對象而不是一對?我怎樣才能比較隨機對象與一對? – 2014-09-10 15:44:11
只要相反,它應該返回一個pairInterface,所以我認爲我應該工作,但編譯器要求在this.snd()和this.fst()之間插入一個分號。這是爲什麼? – 2014-09-10 15:48:31