将对象引用的映射作为键? [英] Map of with object references as keys?

查看:101
本文介绍了将对象引用的映射作为键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,具有关于特定实例的商店信息。为此,我想使用一个映射,但是由于键不是副引用(它们不是,对吗?),而是由 getHashCode 方法。为了更好地理解:

  import collection.mutable._ 
import java.util.Random

object Foo {
var myMap = HashMap [A​​nyRef,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屋!

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