Compare two String arrays in Java

In this post, we will check if two String arrays are equal to one another or not. The two String arrays are considered equal if both arrays have same length, and contains same elements in the same order.

 

1. Comparing Single Dimensional Arrays:

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

 

Download   Run Code

Output:

Both arrays are equal

 
java.util.Arrays class provides two convenient methods for array comparison – equals() and deepEquals(). We can use either method for String array comparison.

 

Download   Run Code

Output:

Both arrays are not equal

 

2. Comparing Multi-Dimensional Arrays:

Similar to single-dimensional array, we can write our own method for checking equality of two multi-dimensional arrays.

 

Download   Run Code

Output:

Both arrays are not equal

 
Arrays.equals() method will not work for multi-dimensional arrays. We should use Arrays.deepEquals() method instead.

 

Download   Run Code

Output:

equals() returns false
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