【问题标题】:How to check if an array of arrays contains a specific array in scala?如何检查数组数组是否包含scala中的特定数组?
【发布时间】:2020-07-15 02:27:09
【问题描述】:

在scala中,如何检查Int的多维数组是否包含数组,例如:

val test = Array(Array(1, 2), Array(2, 1))

test.contains(Array(1, 2)) // this results to false

test.contains(test(0)) // this results to true

所以似乎 scala 也在比较对象引用,在第一种情况下,尽管具有相同的元素,但它是不同的对象,因此返回 false。是这样吗?

在第二种情况下,我正在测试列表中已包含的相同对象之一,因此返回 true。

如何才能达到预期的效果,即检查 Scala 中的多维数组是否包含特定数组?

我已经看到这可以用元组实现,但不能用数组。

【问题讨论】:

标签: scala scala-collections


【解决方案1】:

除非您需要原始性能,通过正确的 measurements 和 jmh 来识别,或者需要 Java 互操作,否则尽量避免使用 Array,而是使用正确的 Scala 集合,例如 List:

List(List(1,2), List(2,1)).contains(List(1,2))  // res2: Boolean = true

如果你必须使用Array,那么试试exists和sameElements的组合,像这样

test.exists(_.sameElements(Array(1,2)))         // res1: Boolean = true

Why doesn't Array's == function return true for Array(1,2) == Array(1,2)?

【讨论】:

  • 或者停止使用无用的数组,改用List或ArraySeq。
【解决方案2】:

你可以使用sameElements:

test.exists(_.sameElements(Array(1, 2)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-03
    • 2020-11-13
    • 2015-06-24
    • 2015-06-26
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多