问题
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....
回答1:
ArrayUtils.isEquals() from Apache Commons does exactly that. It also handles multi-dimensional arrays.
回答2:
You should try Arrays.deepEquals(a, b)
回答3:
Arrays utilities class could be of help for this:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html
There is a method:
equals(Object[] a, Object[] a2)
That compares arrays of objects.
回答4:
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);
}
来源:https://stackoverflow.com/questions/7869050/java-comparing-arrays