Scala: lightweight way to put Arrays in a Set or M

2020-07-09 06:48发布

问题:

Since == does not work with Arrays, I cannot effectively create a Set of Arrays (or Map with Array keys). I would rather not take the performance hit of converting my Arrays to a Vector or List or something. Is there a lightweight way to define natural comparison and hashcode on Arrays so I can stick them in a Set?

回答1:

Use WrappedArray from collection.mutable. It provides proper equality for arrays with a minimal overhead. apply, update etc calls are delegated to underlying array. Also there are special classes for primitive types (e.g. WrappedArray.ofInt) to avoid boxing and unboxing.

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