Array Equality in Java

Write a program to check for array equality in Java. Two arrays are considered to be equal if they contain the same elements in the same order.


 

Comparing two arrays with equals() will return true only when comparing against the same array instance. This is because their equals() implementations is inherited from java.lang.Object. In this post, we will see how we can compare two arrays in Java.

 

1. Comparing an Array of Objects

The two Object arrays are considered equal if

  • Both array references are null or both are non-null, and
  • Both arrays have same type, and
  • Both arrays contain the same number of elements, and
  • All corresponding pairs of objects in the two arrays are equal.

Java

Download   Run Code

Output:

Arrays are not equal

 

2. Comparing Array of Primitives

We can also compare array of primitives using the similar logic:

Java

Download   Run Code

Output:

Arrays are equal

 

3. Using Arrays.equals()

Java Collections framework provides Arrays.equals() utility method for comparing arrays for equality. The method is overloaded for all primitive types and Objects.

Java

Download   Run Code

Output:

Arrays are equal

Arrays.equals() will fail when the array contains a reference type, since this method will internally call equals() on the reference type to determine equality.

 

4. Deep Equality – Arrays.deepEquals()

With nested arrays of arbitrary depth, we can use Arrays.deepEquals() instead that returns true if the two specified arrays are deeply equal to one another.

Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal.

Two possibly null elements e1 and e2 are deeply equal if any of the following conditions hold:

  • e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return true
  • e1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true.
  • e1 == e2
  • e1.equals(e2) would return true.

Java

Download   Run Code

Output:

Arrays are equal

 
References: Arrays Javadoc SE 8

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz