Equals methods when using java arrays

For my equals method, which checks if two arrays are equal, does the first equal method actually check if two arrays are equal or only checks memory addresses? Or should I include both?

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

OR

 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; } } 
+6
source share
3 answers

the = / != operator compares arrays based on their reference, not their contents. Obviously, two arrays can have the same elements, except that they are still two different objects that are created in memory. Arrays are two references. Therefore, your second method should be used as it compares the actual elements inside the two arrays. Also you do not need your 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; } 
+2
source

Another check can also be applied to the first equals method, where it can see that both arrays have the same reference or not. Then another comparison can be made. In the second method, it always checks the element of the array, even if the reference is of the same array. therefore, in terms of performance, this will take time.

 public boolean equals(Object otherObject) { if (otherObject == null) { return false; } else if (getClass() != otherObject.getClass()) { return false; } else if (this != otherObject) return false; } else { RegressionModel otherRegressionModel = (RegressionModel)otherObject; return (xValues == (otherRegressionModel.xValues) && yValues == (otherRegressionModel.yValues)); } } 
+1
source

By adding @Henry to the answer, before comparing the lengths of two given arrays, you must make sure that none of them is null , so that you do not get a NullPointerException .

You can also compare array references before iterating over their elements.

Something like that:

 public static boolean equalArrays(double[] x, double[] y) { if (x == null || y == null || x.length != y.length) { //NOTE: That if both x and y are null we return false despite the fact that you could argue that they are equal return false; } if (x == y) { return true; } for (int index = 0; index < x.length; index++) { if (x[index] != y[index]) { return false; } } return true; } 
+1
source

Source: https://habr.com/ru/post/987003/


All Articles