Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two arrays in Kotlin?

Given some arrays in Kotlin

let a = arrayOf("first", "second") val b = arrayOf("first", "second") val c = arrayOf("1st", "2nd") 

Are there built-in functions to the Kotlin std-lib that tests two arrays for (value) equality for each element?

Thus resulting in:

a.equals(b) // true a.equals(c) // false 

equals() is actually returning false in both cases, but maybe there are built-in functions to Kotlin that one could use?

There is the static function java.utils.Arrays.deepEquals(a.toTypedArray(), b.toTypedArray()) but I would rather prefer an instance method as it would work better with optionals.

like image 791
Lars Blumberg Avatar asked Feb 08 '16 15:02

Lars Blumberg


People also ask

How do you know if two arrays are equal Kotlin?

You can use the contentEquals() function for single dimensional array comparison, which returns true when both arrays are structurally equal. You can even write your custom logic to check for array equality. We can compare two elements for equality with the equals() function.

How do I compare two arrays to each other?

Programmers who wish to compare the contents of two arrays must use the static two-argument Arrays. equals() method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to Object.


1 Answers

In Kotlin 1.1 you can use contentEquals and contentDeepEquals to compare two arrays for structural equality. e.g.:

a contentEquals b // true b contentEquals c // false 

In Kotlin 1.0 there are no "built-in functions to the Kotlin std-lib that tests two arrays for (value) equality for each element."

"Arrays are always compared using equals(), as all other objects" (Feedback Request: Limitations on Data Classes | Kotlin Blog).

So a.equals(b) will only return true if a and b reference the same array.

You can, however, create your own "optionals"-friendly methods using extension functions. e.g.:

fun Array<*>.equalsArray(other: Array<*>) = Arrays.equals(this, other) fun Array<*>.deepEqualsArray(other: Array<*>) = Arrays.deepEquals(this, other) 

P.S. The comments on Feedback Request: Limitations on Data Classes | Kotlin Blog are worth a read as well, specifically comment 39364.

like image 120
mfulton26 Avatar answered Sep 26 '22 23:09

mfulton26