如何在Kotlin中比较两个数组? [英] How to compare two arrays in Kotlin?
问题描述
给出Kotlin中的一些数组
Given some arrays in Kotlin
let a = arrayOf("first", "second")
val b = arrayOf("first", "second")
val c = arrayOf("1st", "2nd")
Kotlin std-lib是否有内置函数可以测试两个数组的每个元素的(值)相等性?
Are there built-in functions to the Kotlin std-lib that tests two arrays for (value) equality for each element?
因此导致:
a.equals(b) // true
a.equals(c) // false
equals()
实际上在两种情况下都返回false
,但是也许Kotlin内置了一个可以使用的函数?
equals()
is actually returning false
in both cases, but maybe there are built-in functions to Kotlin that one could use?
有一个静态函数java.utils.Arrays.deepEquals(a.toTypedArray(), b.toTypedArray())
,但是我宁愿选择一个实例方法,因为它可以与可选方法一起使用.
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.
推荐答案
在Kotlin 1.1中,您可以使用 contentDeepEquals
比较两个数组的结构相等性.例如:
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
在Kotlin 1.0中,没有"Kotlin std-lib的内置函数来测试两个数组的每个元素的(值)相等性."
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).
因此a.equals(b)
仅在a
和b
引用同一数组时才会返回true
.
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.对反馈请求:数据类的限制的评论| Kotlin博客也值得一读,特别是
P.S. The comments on Feedback Request: Limitations on Data Classes | Kotlin Blog are worth a read as well, specifically comment 39364.
这篇关于如何在Kotlin中比较两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!