Java 示例 - 检查两个数组的相等性 问题描述 如何检查两个数组是否相等? 解决方案 下面的例子展示了如何使用Arrays的equals()方法来检查两个数组是否相等。 import java.util.Arrays; public class Main { public static void main(String[] args) throws Exception { int[] ary = {1,2,3,4,5,6}; int[] ary1 = {1,2,3,4,5,6}; int[] ary2 = {1,2,3,4}; System.out.println("Is array 1 equal to array 2?? " +Arrays.equals(ary, ary1)); System.out.println("Is array 1 equal to array 3?? " +Arrays.equals(ary, ary2)); } } 复制 结果 上面的代码示例将产生以下结果。 Is array 1 equal to array 2?? true Is array 1 equal to array 3?? false 复制 解决方案 数组比较的另一个示例 import java.util.Arrays; public class HelloWorld { public static void main (String[] args) { int arr1[] = {1, 2, 3}; int arr2[] = {1, 2, 3}; if (Arrays.equals(arr1, arr2)) System.out.println("Same"); else System.out.println("Not same"); } } 复制 结果 上面的代码示例将产生以下结果。 Same 复制 解决方案 数组比较的另一个示例 public class HelloWorld { public static void main (String[] args) { int arr1[] = {1, 2, 3}; int arr2[] = {1, 2, 3}; if (arr1 == arr2) System.out.println("Same"); else System.out.println("Not same"); } } 复制 结果 上面的代码示例将产生以下结果。 Not same 复制