将对象引用的映射作为键? [英] Map of with object references as keys?
问题描述
映射
,但是由于键不是副引用(它们不是,对吗?),而是由 getHashCode
方法。为了更好地理解: import collection.mutable._
import java.util.Random
object Foo {
var myMap = HashMap [AnyRef,Int]()
def doSomething(ar:AnyRef):Int = {
myMap.get(ar)match {
case Some(x)=> x
case None => {
myMap + = ar - > new Random()。nextInt()
doSomething(ar)
}
}
}
}
object Main {
def main(args:Array [String]){
case class ExampleClass(x:String);
val o1 = ExampleClass(test1)
val o2 = ExampleClass(test1)
println(o2 == o1)// true
println o2 eq o1)// false
//我想要以下两行产生不同的数字
//,我没有控制这些类,搞砸了他们的
//等于实现是不可能的。
println(Foo.doSomething(o1))
println(Foo.doSomething(o2))
}
}
如果我有相同哈希码的实例,随机值的缓存将为两个实例返回相同的值,即使这些不相同。在这种情况下,哪个数据库被使用最好?
澄清/修改
根据 hashCode
和等于
方法,知道如何正常工作。但这正是我想要避免的。我更新了我的例子,使之更清晰。 :)
您还可以使用 IdentityHashMap
连同 scala.collection.JavaConversions
。 p>
I have an object with stores information about specific instances. For that, i would like to use a Map
, but as the keys are not by-reference (they aren't, right?) but as hashes provided by the getHashCode
method. For better understanding:
import collection.mutable._
import java.util.Random
object Foo {
var myMap = HashMap[AnyRef, Int]()
def doSomething(ar: AnyRef): Int = {
myMap.get(ar) match {
case Some(x) => x
case None => {
myMap += ar -> new Random().nextInt()
doSomething(ar)
}
}
}
}
object Main {
def main(args: Array[String]) {
case class ExampleClass(x: String);
val o1 = ExampleClass("test1")
val o2 = ExampleClass("test1")
println(o2 == o1) // true
println(o2 eq o1) // false
// I want the following two lines to yield different numbers
// and i do not have control over the classes, messing with their
// equals implementation is not possible.
println(Foo.doSomething(o1))
println(Foo.doSomething(o2))
}
}
In cases i have instances with the same hash code the "caching" for the random value will return the same value for both instances even those are not same. Which datastructed is used best in this situation?
Clarification/Edit
I know how this works normally, based on the hashCode
and equals
method. But that is exactly what I want to avoid. I updated my example to make that clearer. :)
You can also use IdentityHashMap
together with scala.collection.JavaConversions
.
这篇关于将对象引用的映射作为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!