Arrays Deep2D Equality And Printing
Compare nested arrays with Arrays.deepEquals and print them with deepToString, because equals and toString stop at the outer array reference.
Code
import java.util.Arrays;
public class ArraysDeep2dEquality {
public static void main(String[] args) {
int[][] gridA = { { 1, 2 }, { 3, 4 } };
int[][] gridB = { { 1, 2 }, { 3, 4 } };
// equals 比较的是内层数组引用:两份独立创建的嵌套数组不相等
System.out.println("equals = " + Arrays.equals(gridA, gridB));
// deepEquals 递归比较内层内容
System.out.println("deepEquals = " + Arrays.deepEquals(gridA, gridB));
// Arrays.toString 对二维数组只打印引用样式,别用它断言内容
// deepToString 才会展开每一层
System.out.println("deepToString = " + Arrays.deepToString(gridA));
// deepHashCode 与 deepEquals 配套,同样递归
System.out.println("deepHashCode equal = "
+ (Arrays.deepHashCode(gridA) == Arrays.deepHashCode(gridB)));
gridB[1][0] = 30; // 改一个内层元素后内容不再相等
System.out.println("after edit deepEquals = " + Arrays.deepEquals(gridA, gridB));
}
}How it works
One way to read it: the class ArraysDeep2dEquality and the function main, doing all the work.
Watch out for
- Each symbol resolves to a language built-in, so nothing is fetched.
Using it
Signature: public static void main(String[] args)
The demo output is labeled (equals =, deepEquals =, deepToString =), and the labels walk you through the sequence.
Key statements
int[][] gridA = { { 1, 2 }, { 3, 4 } };
int[][] gridB = { { 1, 2 }, { 3, 4 } };
gridB[1][0] = 30; // 改一个内层元素后内容不再相等
System.out.println("after edit deepEquals = " + Arrays.deepEquals(gridA, gridB));
Interactive Tools for This Topic
FAQ
- What does Arrays Deep2D Equality And Printing print when run?
- Running the file directly is enough — expect labeled output lines such as `equals =`, `deepEquals =`, `deepToString =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.