在Java中,如何比較兩個陣列?
範例
以下範例使用equals
方法來檢查兩個陣列是否相等。
package com.yiibai;
import java.util.*;
public class CompareArrays {
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