Java如何比較兩個陣列是否相等？

2019-10-16 22:31:08

``````package com.yiibai;

import java.util.*;

public class CheckArrayEquality {
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
``````

範例2

``````package com.yiibai;

import java.util.Arrays;

public class CheckArrayEquality2 {
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
``````

範例3

``````package com.yiibai;

public class CheckArrayEquality3 {
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
``````