Scala:将数组放入Set或Map的轻量级方法

Jay*_*ker 8 arrays scala equals set hashcode

由于==不能使用Arrays,我无法有效地创建一组数组(或使用数组键映射).我宁愿不把我的数组转换为Vector或List或其他东西.有没有一种轻量级的方法来定义Arrays上的自然比较和哈希码,所以我可以将它们粘贴在一个Set中?

mis*_*tor 11

使用WrappedArraycollection.mutable.它为具有最小开销的数组提供了适当的相等性.apply,update等的呼叫委托给底层数组.还有基本类型的特殊类(例如WrappedArray.ofInt),以避免装箱和拆箱.

scala> new WrappedArray.ofInt(Array(2, 3, 4))
res35: scala.collection.mutable.WrappedArray.ofInt = WrappedArray(2, 3, 4)

scala> new WrappedArray.ofInt(Array(2, 3, 4))
res36: scala.collection.mutable.WrappedArray.ofInt = WrappedArray(2, 3, 4)

scala> res35 == res36
res37: Boolean = true
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`genericWrapArray(Array(2,3,4))`,它位于`Predef`中,因此您不需要导入 (3认同)