Scala:将数组放入Set或Map中的轻巧方式 [英] Scala: lightweight way to put Arrays in a Set or Map

查看:269
本文介绍了Scala:将数组放入Set或Map中的轻巧方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于==不适用于数组,因此我无法有效地创建一组数组(或带有数组键的Map).我宁愿不承受将数组转换为Vector或List或其他东西的性能损失.是否有一种轻量级的方法来定义数组上的自然比较和哈希码,以便我可以将它们粘贴到集合中?

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?

推荐答案

使用

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

这篇关于Scala:将数组放入Set或Map中的轻巧方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆