Map of with object references as keys?

前端 未结 3 1770
[愿得一人]
[愿得一人] 2021-01-14 17:37

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, rig

3条回答
  •  我在风中等你
    2021-01-14 18:32

    Ah based on comment... You could use a wrapper that overrides equal to have reference semantics.

    class EqWrap[T <: AnyRef](val value: T) {
      override def hashCode() = if (value == null) 0 else value.hashCode
      override def equals(a: Any) = a match {
        case ref: EqWrap[_] => ref.value eq value
        case _ => false
      }
    }
    object EqWrap {
      def apply[T <: AnyRef](t: T) = new EqWrap(t)
    }
    
    case class A(i: Int)
    
    val x = A(0)
    val y = A(0)
    
    val map = Map[EqWrap[A], Int](EqWrap(x) -> 1)
    val xx = map.get(EqWrap(x))
    val yy = map.get(EqWrap(y))
    //xx: Option[Int] = Some(1)
    //yy: Option[Int] = None
    

    Original answer (based on not understanding the question - I have to leave this so that the comment makes sense...)

    Map already has this semantic (unless I don't understand your question).

    scala> val x = A(0)
    x: A = A(0)
    
    scala> val y = A(0)
    y: A = A(0)
    
    scala> x == y
    res0: Boolean = true // objects are equal
    
    scala> x.hashCode
    res1: Int = -2081655426
    
    scala> y.hashCode
    res2: Int = -2081655426 // same hash code
    
    scala> x eq y
    res3: Boolean = false // not the same object
    
    scala> val map = Map(x -> 1)
    map: scala.collection.immutable.Map[A,Int] = Map(A(0) -> 1)
    
    scala> map(y)
    res8: Int = 1 // return the mapping based on hash code and equal semantic
    

提交回复
热议问题