Java的:如何来测试阵列平等? [英] Java: How to test on array equality?
问题描述
为什么以下code印花不同。
?
布尔[] [] A = {{假,真},{真,假}};
布尔[] [] B = {{假,真},{真,假}};如果(满足Arrays.equals(A,B)||一个== B)
的System.out.println(平等);
其他
的System.out.println(不同。);
为什么以下code印花
不同。
?的
块引用>由于<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#equals%28boolean[],%20boolean[]%29\"><$c$c>Arrays.equals$c$c>执行的浅的比较。因为数组继承其
等于
-method从对象
,身份比较将用于内部阵列中进行,这将失败,因为A
和b
不参考的相同的阵列。如果您更改为<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#deepEquals%28java.lang.Object[],%20java.lang.Object[]%29\"><$c$c>Arrays.deepEquals$c$c>它会打印
平等的。
预期。Why is the following code printing
"Different."
?boolean[][] a = { {false,true}, {true,false} }; boolean[][] b = { {false,true}, {true,false} }; if (Arrays.equals(a, b) || a == b) System.out.println("Equal."); else System.out.println("Different.");
解决方案Why is the following code printing
"Different."
?Because
Arrays.equals
performs a shallow comparison. Since arrays inherit theirequals
-method fromObject
, an identity comparison will be performed for the inner arrays, which will fail, sincea
andb
do not refer to the same arrays.If you change to
Arrays.deepEquals
it will print"Equal."
as expected.这篇关于Java的:如何来测试阵列平等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!