How to compare two arrays in Java?

Java Programming Java 8Object Oriented Programming

Arrays can be compared using following ways in Java

  • Using Arrays.equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method.

  • Using Arrays.deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

Using == on array will not give the desired result and it will compare them as objects. See the example below for each of the comparison way.

Example

 Live Demo

import java.util.Arrays;

public class Tester{
   public static void main(String[] args) {
      int[] array1 = {1, 2, 3};
      int[] array2 = {1, 2, 3};

      System.out.println("Arrays: array1 = [1, 2, 3], array 2 = [1, 2, 3]");
      //Scenario 1 : Comparing using ==
      System.out.println("== results: " + (array1 == array2));

      //Scenario 2 : Comparing using Arrays.equals()
      System.out.println("Arrays.equals() results: " + Arrays.equals(array1,array2));

      Object[] objArray1 = {array1};
      Object[] objArray2 = {array2};

      System.out.println("Arrays: objArray1 = {array1}, objArray1 = {array2}");
      //Scenario 3 : Comparing using Arrays.equals()
      System.out.println("Arrays.equals() results: " + Arrays.equals(objArray1,objArray2));

      //Scenario 4 : Comparing using Arrays.deepEquals()
      System.out.println("Arrays.deepEquals() results: " + Arrays.deepEquals(objArray1,objArray2));

   }
}

Output

Arrays: array1 = [1, 2, 3], array 2 = [1, 2, 3]
== results: false
Arrays.equals() results: true
Arrays: objArray1 = {array1}, objArray1 = {array2}
Arrays.equals() results: false
Arrays.deepEquals() results: true
raja
Published on 30-Aug-2018 08:13:56
Advertisements