Compare two integer arrays in Java

In this post, we will check if two integer arrays are equal to one another or not.

 
The two integer arrays are considered equal if both arrays contain the same number of elements, and contains same elements in the same order.

 

Compare Single Dimentional arrays:

Naive solution would be to write our own method for checking array equality.

 

Download   Run Code

Output:

Given arrays are equal

 
We can also take advantage of two convenient methods provided by java.util.Arrays class for array comparison – equals() and deepEquals(). Both these methods are overloaded to accept all primitive types and an array of Objects.

 

Download   Run Code

Output:

Given arrays are not equal

 

Compare 2-Dimentional arrays:

Similar to 1D array, we can write our own method for checking array equality.

 

Download   Run Code

Output:

Both arrays are not equal

 
For multi-dimensional arrays, Arrays.equals() won’t work. We need to use Arrays.deepEquals().

 

Download   Run Code

Output:

Arrays.equals() returns false
Arrays.deepEquals() returns true

 
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

avatar
  Subscribe  
Notify of