附上我在javarevisited.blogspot.in上找到的一个非常好的例子。
public class ArrayCompareTest {
public static void main(String args[]) {
int[] i1 = new int[] {1,2,3,4};
int[] i2 = new int[] {1,2,3,4};
int[] i3 = new int[] {0,2,3,4};
boolean result = Arrays.equals(i1, i2);
System.out.println("Comparing int array i1: " + Arrays.toString(i1)
+ " and i1: " + Arrays.toString(i2));
System.out.println("Does array i1 and i2 are equal : " + result);
result = Arrays.equals(i2, i3);
System.out.println("Comparing int array i2: " + Arrays.toString(i2)
+ " and i3: " + Arrays.toString(i3));
System.out.println("Does array i2 and i3 are equal : " + result);
double[] d1 = new double[] {1.5, 2.4, 3.2, 4,1};
double[] d2 = new double[] {1.5, 2.4, 3.2, 4,1};
double[] d3 = new double[] {0.0, 2.4, 3.2, 4,1};
result = Arrays.equals(d1, d2);
System.out.println("Comparing double array d1: " + Arrays.toString(d1)
+ " and d2: " + Arrays.toString(d2));
System.out.println("Does double array d1 and d2 are equal : " + result);
result = Arrays.equals(d2, d3);
System.out.println("Comparing double array d2: " + Arrays.toString(d2)
+ " and d3: " + Arrays.toString(d3));
System.out.println("Does double array d2 and d3 are same : " + result);
String[] s1 = new String[]{"One", "Two", "Three"};
String[] s2 = new String[]{"One", "Two", "Three"};
String[] s3 = new String[]{"zero", "Two", "Three"};
result = Arrays.equals(s1, s2);
System.out.println("Comparing two String array s1: " + Arrays.toString(s1)
+ " and s2: " + Arrays.toString(s2));
System.out.println("Are both String array s1 and s2 are equal : " + result);
result = Arrays.equals(d2, d3);
System.out.println("Comparing two String array s2: " + Arrays.toString(s2)
+ " and s3: " + Arrays.toString(s3));
System.out.println("Are both String array s2 and s3 are equal : " + result);
Object[] o1 = new Object[]{"one", new String[]{"two"}};
Object[] o2 = new Object[]{"one", new String[]{"two"}};
System.out.println("Object array o1: " + Arrays.toString(o1) + " and o2: "
+ Arrays.toString(o2));
System.out.println("Comparing Object Array o1 and o2 with Arrays.equals : "
+ Arrays.equals(o1, o2));
System.out.println("Comparing Object Array o1 and o2 with Arrays.deepEquals : "
+ Arrays.deepEquals(o1, o2));
}
}
输出:
比较整数数组 i1: [1, 2, 3, 4] 和 i1: [1, 2, 3, 4]
i1 和 i2 数组是否相等:true
比较整数数组 i2: [1, 2, 3, 4] 和 i3: [0, 2, 3, 4]
i2 和 i3 数组是否相等:false
比较双精度浮点数数组 d1: [1.5, 2.4, 3.2, 4.0, 1.0] 和 d2: [1.5, 2.4, 3.2, 4.0, 1.0]
d1 和 d2 数组是否相等:true
比较双精度浮点数数组 d2: [1.5, 2.4, 3.2, 4.0, 1.0] 和 d3: [0.0, 2.4, 3.2, 4.0, 1.0]
d2 和 d3 数组是否相等:false
比较两个字符串数组 s1: [One, Two, Three] 和 s2: [One, Two, Three]
判断字符串数组 s1 和 s2 是否相等:true
比较两个字符串数组 s2: [One, Two, Three] 和 s3: [zero, Two, Three]
判断字符串数组 s2 和 s3 是否相等:false
对象数组 o1: [one, [Ljava.lang.String;@19821f] 和 o2: [one, [Ljava.lang.String;@addbf1]
使用 Arrays.equals 比较对象数组 o1 和 o2:false
使用 Arrays.deepEquals 比较对象数组 o1 和 o2:true