Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
deep
shallow
equal

How to test array equality in Java

Educative Answers Team

Two arrays are equal if all their values are equal and in the same order.

svg viewer

Arrays.equals()

The Arrays.equals method can be used to check if two arrays are equal.

This method takes two arrays as arguments.

import java.util.Arrays;

class ArrayEquality {
    public static void main( String args[] ) {
        int [] arr1 = new int [] {20, 5, -95, 43, 17};
        int [] arr2 = new int [] {20, 5, -95, 43, 17};
        System.out.println(Arrays.equals(arr1, arr2));
    }
}

Note that a shallow comparison is performed, i.e., it checks:

arr1[0].equals(arr2[0]),
arr1[1].equals(arr2[1]),
...

This is not suitable for multidimensional arrays.

Arrays.deepEquals()

The Arrays.deepEquals() method is a more effective way of testing the equality of multidimensional arrays.

This method takes two arrays as arguments.

import java.util.Arrays;

class ArrayEquality {
    public static void main( String args[] ) {
        int [][] arr1 = {{20, 5}, 
                         {-95, 43}, 
                         {17, 22}};
        int [][] arr2 = {{20, 5}, 
                         {-95, 43}, 
                         {17, 22}};

        System.out.println(Arrays.deepEquals(arr1, arr2));
    }
}

This method recurses on the arrays and compares the actual elements. It can be used with single-dimension arrays as well.

RELATED TAGS

array
deep
shallow
equal
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring