家庭作业帮助,Java 对类



我有一个家庭作业来比较我在类中创建的通用对,并将其发送到测试器类进行比较,它应该返回 true。我不知道我做错了什么。我认为在尝试比较两个对象时,这可能是我的平等方法。当我认为我走在正确的轨道上时,我会收到StackOverflow异常。这是我代码的一部分:

import java.util.ArrayList;
public class Pair<T1,T2> implements PairInterface<T1,T2>
{
    private T1 aFirst;
    private T2 aSecond;
    Pair p1 = new Pair(aFirst,aSecond);
    public Pair(T1 aFirst, T2 aSecond)
    {
            this.aFirst = aFirst;
            this.aSecond = aSecond;
    }
    /**
     * Gets the first element of this pair.
     * @return the first element of this pair.
     */
    public T1 fst()
    {
        return aFirst;
    }
    /**
     * Gets the second element of this pair.
     * @return the second element of this pair.
     */
    public T2 snd()
    {
        return aSecond;
    }
    /**
     * Sets the first element to aFirst.
     * @param aFirst  the new first element
     */
    public void setFst(T1 aFirst)
    {
        this.aFirst = aFirst;
    }
    /**
     * Sets the second element to aSecond.
     * @param aSecond  the new second element
     */
    public void setSnd(T2 aSecond)
    {
        this.aSecond = aSecond;
    }
    /**
     * 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.
     */
        @Override
    public boolean equals(Object otherObject)
    {
        Pair p2 = (Pair) otherObject;
        if(otherObject == null)
        {
            return false;
        }
        if(getClass() != otherObject.getClass())
        {
            return false;
        }
                if(p1.equals(p2)){
                    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.
     * @return a string representing this pair.
     */
        @Override
    public String toString()
    {
        return new StringBuilder().append('(').append(fst()).append(',').append(snd()).appen         d(')').toString();
    }
}

首先,为什么要创建类的新实例?

Pair p1 = new Pair(aFirst,aSecond);

你应该这样做,当使用构造函数创建对象时,你的字段将被初始化。

其次,你在equals

方法中有一个递归问题,它在自身内部调用equals。

您必须将等于方法更改为类似的东西

Pair p2 = (Pair) otherObject;
      if (otherObject == null) {
         return false;
      }
      if (this == otherObject) {
         return true;
      }
      if (getClass() != otherObject.getClass()) {
         return false;
      }
      return this.aFirst.equals(p2.aFirst)
            && this.aSecond.equals(p2.aSecond);

>StackOverFlowException(大多数时候)以递归(提示)的形式抛出。

看看你的'equals(

)'方法:如果q1.equals(q2),你就会检查。
等于调用等于...(它将使用相同的方法检查 Q2 是否等于 Q1)

要解决它,您必须使用equals方法,而无需在其中再次使用"等于"。

我们是怎么做到的?
好吧,您想知道两个对象中的值是否相等。
您应该重写它并检查值是否相等,而不是它们本身的对象,至少不是equals()

最新更新