I have two Arrays of unknown type...is there a way to check the elements are the same:
public static boolean equals(Object a , Object b) {
if (a instanceof int[])
return Arrays.equals((int[]) a, (int[])b);
if (a instanceof double[]){
////etc
}
I want to do this without all the instanceof checks....
Java provides a direct method Arrays. equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java).
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
Emanuel Maliaño when comparing String values in Java you need to use the equals() method. The use of the comparison operator "==" will only return true if they are the same object in memory which is not guaranteed even with a direct comparison of literal Strings.
Arrays. equals(double[] a, double[] a2) method returns true if the two specified arrays of doubles are equal to one another. Two arrays are equal if they contain the same elements in the same order.
If the array type is unknown, you cannot simply cast to Object[]
, and therefore cannot use the methods (equals
, deepEquals
) in java.util.Arrays
.
You can however use reflection to get the length and items of the arrays, and compare them recursively (the items may be arrays themselves).
Here's a general utility method to compare two objects (arrays are also supported), which allows one or even both to be null:
public static boolean equals (Object a, Object b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
if (a.getClass().isArray() && b.getClass().isArray()) {
int length = Array.getLength(a);
if (length > 0 && !a.getClass().getComponentType().equals(b.getClass().getComponentType())) {
return false;
}
if (Array.getLength(b) != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (!equals(Array.get(a, i), Array.get(b, i))) {
return false;
}
}
return true;
}
return a.equals(b);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With