Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 772
Jay Hacker Avatar asked Nov 21 '11 22:11

Jay Hacker


1 Answers

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
like image 108
missingfaktor Avatar answered Sep 17 '22 23:09

missingfaktor