[英]Comparing key of hash map in Scala
I need to read some Scala code (starting from a few hours ago), I also need to make sure how hash maps in Scala compares keys. 我需要阅读一些Scala代码(从几个小时前开始),我还需要确保Scala中的哈希映射如何比较密钥。 After reading some posts, I know that the
==
is for value comparison, but it is not clear that hash maps (eg scala.collection.immutable.Map
) keys are compared using value comparison ( ==
) or reference comparison? 在阅读了一些帖子后,我知道
==
是用于值比较,但是不清楚哈希映射(例如scala.collection.immutable.Map
)键是使用值比较( ==
)还是参考比较来比较的?
The HashMap
uses ==
and the hashing method ##
to compare keys. HashMap
使用==
和散列方法##
来比较密钥。 It couldn't use the reference because then something like Map(List(1) -> 'a, List(1) -> 'b)
would contain two entries, which would be wrong. 它不能使用引用因为那样像
Map(List(1) -> 'a, List(1) -> 'b)
这样的东西会包含两个条目,这是错误的。
See source code (it is on web site): 查看源代码(在网站上):
http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.HashMap http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.HashMap
I wrote simple test case (scala 2.9.1 on eclipse). 我写了一个简单的测试用例(eclipse上的scala 2.9.1)。 You can debug it on eclipse - the lines of source code are the same like on api site.
您可以在eclipse上调试它 - 源代码行与api站点上的相同。
class EqualsTest {
case class Key(private val value: Int) {
override def hashCode() = value
override def equals(other: Any) = other match {
case that: Key => that.value == value
case _ => false
}
}
@Test
def test() {
val map = Map(Key(1)->1,Key(2)->3,Key(4)->5,Key(5)->2,Key(9)->9)
val key = Key(1)
val value = map.get(key) //add breakpoint here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.