如何在 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 中你可以使用 contentEquals
和 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."
数组总是使用 equals()
进行比较,就像所有其他对象一样"(反馈请求:数据类限制 | Kotlin 博客).
"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.
但是,您可以使用 extension 创建自己的可选"友好方法功能.例如:
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)
附言Feedback Request: Limitations on Data Classes 上的评论|Kotlin 博客也值得一读,特别是评论 39364.
P.S. The comments on Feedback Request: Limitations on Data Classes | Kotlin Blog are worth a read as well, specifically comment 39364.
这篇关于如何在 Kotlin 中比较两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!