Javaexamples-arrays-equal

提供:Dev Guides
移動先:案内検索

Javaの例-2つの配列の等価性を確認します

問題の説明

2つの配列が等しいかどうかを確認する方法は?

溶液

次の例は、配列のequals()メソッドを使用して、2つの配列が等しいかどうかを確認する方法を示しています。

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