对于检查两个数组是否相等的 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));
}
}
或
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;
}
}
最佳答案
=
/!=
运算符根据引用而不是内容比较数组。显然,两个数组可能具有相同的元素,只是它们仍然是在内存中创建的两个不同的对象。数组是两个引用。因此,您的应该应用第二种方法,因为它比较两个数组中的实际元素。此外,您不需要 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;
}
关于java - 使用数组java时的equals方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30179652/