Checking if Two Arrays are Equal in Java

Learn to compare two arrays using different techniques in Java. We will learn the array comparison from using simple for loops to inbuilt Java APIs.

1. How Arrays Comparison is Done?

In Java or any other programming language, the basics behind comparing two arrays are the same. Two arrays are equal if:

  • both are either null or non-null.
  • both are of the same type.
  • both have an equal number of items.
  • both have the same item in the corresponding indices in the same order.
  • both arrays are multi-dimensional then inner arrays also need to be equal.

Now when we know what makes two arrays equal, it is easy to write a function that will check it.

2. Checking Array Equality with java.util.Arrays

2.1. API Methods

For any kind of problem, if you have a Java API available within JDK, always prefer to use it rather than writing it yourself. You should write a new function only when you have a very strong reason to do it, else use the inbuilt APIs.

Arrays class provides many useful methods for operating on arrays. For checking array equality, it provides two methods that have multiple overloaded forms to accept different array types:

  • public static boolean equals(array1, array2) : returns true if array1 and array2 are equal to one another i.e. they contain the same elements in the same order.
  • public static boolean equals(array1, array2, comparator) : returns true if array1 and array2 are equal to one another. Two array items e1 and e2 are considered equal if comparator.compare(e1, e2) == 0.
  • public static boolean deepEquals(array1, array2) : returns true if array1 and array2 are deeply equal to one another. This method is appropriate for use with nested arrays of arbitrary depth.

2.2. Simple Arrays

The simple arrays are 1-D arrays that are not nested. In simple arrays, we can have any type of item and it is necessary to understand how to deal with them.

  • Primitive and String Arrays : Primitives and strings are always compared by their value so we can safely use the equals() API.
  • Object Types : In this case, we need to know how the two array items will be checked for equality. If the default object eqaulity has to be used, or class has overidden the Object.equals() method then we can use the Arrays.equals(), else we mut use the Comparator verion of API to provide the custom object equality logic.
String[] a1 = {"A", "B", "C"};
String[] a2 = {"A", "B", "C"};
String[] a3 = {"X", "Y", "Z"};

boolean matches = Arrays.equals(a1, a2);  //true

matches = Arrays.equals(a1, a3);  //false

2.3. Nested Arrays

To check nested array’s equality, we must use the deepEquals() API.

It is important to note that deepEquals() only works with object types, so deepEquals() cannot be used with primitive arrays but we can use it for any kind of simple or nested arrays.

String[][] a4 =
    {
        {"A", "B", "C"},
        {"X", "Y", "Z"}
    };

String[][] a5 =
    {
        {"A", "B", "C"},
        {"X", "Y", "Z"}
    };

boolean matches = Arrays.deepEquals(a4, a5);  //true

3. Array Comparison with ‘For-loop’

For some reason, if we are not able to use the Arrays methods, we can write our own method and add the custom logic there.

For example, we do not declare arrays equal if both arrays are null. In this case, we can write our own function where we iterate over array items in a for loop and compare the items one by one. There may be more compelling reasons for others.

In the following method checkArrayEqualityWithForLoop(), we are writing the code for checking the equality of two simple arrays. Feel free to modify the logic as you want.

public static boolean checkArrayEqualityWithForLoop(String[] a1,
                                                    String[] a2) {
	if (a1 == a2) {
	  return true;
	}

	if (a1 == null || a2 == null) {
	  return false;
	}

	int n = a1.length;
	if (n != a2.length) {
	  return false;
	}

	for (int i = 0; i < n; i++) {
	  if (!a1[i].equals(a2[i])) {
	    return false;
	  }
	}
	return true;
}

4. Array Comparison with Stream API

To make code more readable, we can use the stream API’s IntStream.range() API in place of the for-loop. Else the remaining logic is same as the previous example.

public static boolean checkEqualityWithStream(String[] a1,
	                                          String[] a2) {
	if (a1 == a2) {
	  return true;
	}

	if (a1 == null || a2 == null
	    || a1.length != a2.length) {
	  return false;
	}

	return IntStream.range(0, a1.length)
	    .allMatch(i -> a1[i].equals(a2[i]));
}

5. Conclusion

In this tutorial, we learned to check if two arrays are equal in Java. We learned the rules to check the equality of simple arrays and nested arrays. Also, we learned to take care of equality of array items using Object.equals() and Comparator.

Finally, we learned to use the Java APIs and well the simple for-loop for customizing the array equality logic.

Happy Learning !!

Sourcecode on Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.