如何在 Scala 中声明一组排序的整数数组?

How to declare a sorted set of array of ints in Scala?

我已经为 scala.collection.mutable.SortedSet 尝试了以下所有方法:

var s = SortedSet[Array[Int]]
var s = SortedSet[Array[Int]]()
var s = new SortedSet[Array[Int]]
var s = new SortedSet[Array[Int]]()
var s = SortedSet[Array]
var s = SortedSet[Array]()
var s = new SortedSet[Array]()

我不知道为什么只在 Scala 中声明这些东西就这么难。我想要的只是一组排序的 Int 数组。

SortedSet 不是 "default" 集合,因此未在 Predef 中定义。

首先导入它然后它应该可以工作:

import scala.collection.SortedSet
val s = SortedSet[Array[Int]]()

接下来您需要定义隐式排序:

implicit val arrayOrdering = new Ordering[Array[Int]] {
   override def compare(x: Array[Int], y: Array[Int]): Int = ???
     // Implement whatever you mean by one array is greater than the other array
}

还要小心 Array-s 因为它是一个 Java 数组,所以它没有覆盖 equalshashcode 方法并且看起来不值相等,而是引用相等。