等于使用数组java时的方法

rre*_*101 6 java arrays equals

对于检查两个数组是否相等的我的equals方法,第一个方法"equals"是否实际检查两个数组是否相等还是仅测试内存地址?或者我应该包括两者?

   public boolean equals(Object otherObject)
    {
       if (otherObject == null)
       {
           return false;
       }
       else if (getClass() != otherObject.getClass())
       {
           return false;
       }
       else
       {
          RegressionModel otherRegressionModel = (RegressionModel)otherObject;
          return (xValues == (otherRegressionModel.xValues) && yValues == (otherRegressionModel.yValues));
       }
    }
Run Code Online (Sandbox Code Playgroud)

要么

public static boolean equalArrays(double[] x, double[] y)
{
    if(x.length != y.length)
    {
        return false;
    }
    else
    {
        for(int index = 0; index < x.length; index++)
        {
            if (x[index] != y[index])
            {
                return false;
            }
        }
        return true;             
    }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*Zhu 2

=/运算符!=根据数组的引用而不是其内容来比较数组。显然,两个数组可能具有相同的元素,只不过它们仍然是在内存中创建的两个不同的对象。数组是两个引用。因此,应该应用第二种方法,因为它比较两个数组内的实际元素。而且你也不需要你的else声明。

public static boolean equalArrays(double[] x, double[] y)
{
    if(x.length != y.length)
    {
        return false;
    }
    for (int index = 0; index < x.length; index++)
    {
        if (x[index] != y[index])
        {
            return false;
        }
    }
    return true;             
}
Run Code Online (Sandbox Code Playgroud)