检查对是否相等

时间:2015-01-15 19:49:00

标签: java equals

这应该是一个非常简单的程序,但是每当我尝试编译它时,我都会收到错误,指出找不到otherObject.fstotherObject.snd变量,所以我的equals方法不是好好工作。其他一切都很好。我认为我的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()+")";
    }
}

1 个答案:

答案 0 :(得分:2)

otherObject被声明为Object类型,因此它不具有您创建的任何类的任何属性。它应该与您尝试将其进行比较的对象类型相同。

相关问题