2015-01-15 181 views
-1

这应该是一个非常简单的程序,但是无论何时我尝试编译它,我都会收到一个错误消息,指出找不到otherObject.fstotherObject.snd变量,所以我的等号方法无法正常工作。其他一切工作正常。我相信这是我的setFstsetSnd方法的问题。我试过了一堆变体,但我似乎无法正确地说出它。任何帮助将非常感激!检查对是否相等

public class Pair<T1, T2> implements PairInterface<T1, T2> 
{ 
    // TO DO: Instance Variables 
    public T1 first; 
    public T2 second; 
    public T1 fst; 
    public T2 snd; 

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

    /** 
    * Sets the first element to aFirst. 
    * @param aFirst the new first element 
    */ 
    public void setFst(T1 aFirst) 
    { 
     // TO DO 
     aFirst = fst; 
    } 

    /** 
    * Sets the second element to aSecond. 
    * @param aSecond the new second element 
    */ 
    public void setSnd(T2 aSecond) 
    { 
     // TO DO 
     aSecond = snd; 
    } 

    /** 
    * 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; 
     } 
     if (otherObject.fst.equals(this.fst) && otherObject.snd.equals(this.snd)) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
     // TO DO 
    } 

    /** 
    * 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. 
    * @return a string representing this pair. 
    */ 
    public String toString() 
    { 
     // TO DO 
     return "("+first.toString()+","+second.toString()+")"; 
    } 
} 
+0

我从来没有听说过有'fst'成员的'Object';)。我非常肯定你正在寻找投射,而是使用'fst()'和'snd()'来代替。 –

回答

2

otherObject被声明为只是一个Object类型,所以它没有你创建的任何类的任何属性。它应该与您试图比较的对象类型相同。

+0

这样做的伎俩,不能相信我错过了我一直在挠我的头几个小时。谢谢! –