Java数组比较 [英] Java Array Comparison
问题描述
在Java中的工作,让我们说我有两个对象,这要归功于 obj.getClass()。IsArray的()
,我知道都是数组。让我们进一步说,我想这两个数组相互比较 - 可能通过使用满足Arrays.equals
。有没有一种优雅的方式来做到这一点,而不诉诸一个大详尽的if / else树找出哪些满足Arrays.equals
的味道就要用?我在寻找的东西,比这少的碍眼的:
如果(OBJ1的instanceof的byte [] && OBJ2的instanceof的byte []){
返回满足Arrays.equals((字节[])OBJ1,(字节[])OBJ2);
}
否则,如果(OBJ1的instanceof布尔[] && OBJ2的instanceof布尔[]){
...
您可以使用反射。
公共静态布尔arrayEquals(对象ARR1,对象ARR2)抛出异常{
类<> C = arr1.getClass();
如果(!c.getComponentType()。isPrimitive()){
C = [对象]类;
}
方法M = Arrays.class.getMethod(等于,C,C);
回报(布尔)m.invoke(NULL,ARR1,ARR2);
}
反射仅用于查找在运行时没有你正在寻找避免碍眼正确的方法;实际满足Arrays.equals
方法应该跑得快pretty。
显然,量产版需要更强大的异常处理。您也可以使用 deepEquals(Object []对象,对象[])
而不是等于(Object []对象,对象[])
非基本数组。
Working within Java, let's say I have two objects that, thanks to obj.getClass().isArray()
, I know are both arrays. Let's further say that I want to compare those two arrays to each other -- possibly by using Arrays.equals
. Is there a graceful way to do this without resorting to a big exhaustive if/else tree to figure out which flavor of Arrays.equals
needs to be used? I'm looking for something that's less of an eyesore than this:
if (obj1 instanceof byte[] && obj2 instanceof byte[]) {
return Arrays.equals((byte[])obj1, (byte[])obj2);
}
else if (obj1 instanceof boolean[] && obj2 instanceof boolean[]) {
...
You can use reflection.
public static boolean arrayEquals(Object arr1, Object arr2) throws Exception {
Class<?> c = arr1.getClass();
if (!c.getComponentType().isPrimitive()) {
c = Object[].class;
}
Method m = Arrays.class.getMethod("equals", c, c);
return (Boolean) m.invoke(null, arr1, arr2);
}
Reflection is only used to find the right method at run-time without the eyesore you're looking to avoid; the actual Arrays.equals
method should run pretty fast.
Obviously production version needs more robust exception handling. You may also want to use deepEquals(Object[], Object[])
instead of equals(Object[], Object[])
for non-primitive arrays.
这篇关于Java数组比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!