This post will discuss how to determine whether two arrays are equal to each other in Kotlin. Two arrays are considered equal if they contain the same number of same elements in the same order.

1. Single Dimensional Arrays

Kotlin 1.1 introduced extension functions for element-by-element operations on arrays. You can use the contentEquals() function for single dimensional array comparison, which returns true when both arrays are structurally equal.

Download Code

Output:

Arrays are equal

 
Since the extension functions are infix, you can use them in the following way:

Download Code

Output:

Arrays are equal

 
You can even write your custom logic to check for array equality. We can compare two elements for equality with the equals() function. The algorithm can be implemented as follows in Kotlin.

Download Code

Output:

Arrays are equal

2. Two-Dimensional Arrays

Similar to the single-dimensional array, you can write our utility function for checking the array equality.

Download Code

Output:

Arrays are equal

3. Multi-Dimensional Arrays

You can use the contentDeepEquals() function for multidimensional arrays, which returns true if the two specified arrays are deeply equal.

Download Code

Output:

Arrays are equal

4. Array of Objects

The two object arrays are considered equal if

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

 
An easy way to compare two arrays of objects is to use the contentEquals() function and have your class override the equals() and hashCode() methods. Alternatively, you can use a data class that automatically derives the equals() and hashCode().

Download Code

Output:

Arrays are equal

That’s all about comparing two arrays for equality in Kotlin.