java - Scala 案例类构造函数问题

标签 java scala hashcode

我对 Scala 中的一些东西感到困惑。我似乎有具有相同地址但内容不同的对象。我在使用 Kiama 时遇到了这个问题。但为了简单起见,我将所有代码归结为:

object CaseTests {
  trait Attributable extends Product {
    var parent: Attributable = null;

    private def setChildConnections = {
        var i : Int = 0        
        for (i <- 0 until productArity) {
            productElement (i) match {
                case c : Attributable => c.parent = this
                case _ => 
            }
        }

    }
    setChildConnections
  }

  abstract class Tree extends Attributable { def id = super.toString }
    case class Pair (left : Tree, right : Tree) extends Tree { println(this+" = "+super.toString + " = ("+left.id+", "+right.id+")"); }
    case class Leaf (value : Int) extends Tree { println(this+" = "+super.toString); }

  def main(args: Array[String]): Unit = {
      val l1 = Leaf(1);
      val l2 = Leaf(1);
      val tree = Pair (Leaf (1), Pair (Leaf (1), Leaf (2)))
      val Pair(left1: Tree, sub: Tree) = tree
      val Pair(left2: Tree, right: Tree) = sub 
      println("left1 = "+left1.id)
      println("left2 = "+left2.id)
      println("left1.parent = "+left1.parent)
      println("left2.parent = "+left2.parent)
  }
}

当我运行测试用例时,我得到以下输出:

Leaf(1) = org.modelica.v4.tests.full.CaseTests$Leaf@fe67d8d2
Leaf(1) = org.modelica.v4.tests.full.CaseTests$Leaf@fe67d8d2
Leaf(1) = org.modelica.v4.tests.full.CaseTests$Leaf@fe67d8d2
Leaf(1) = org.modelica.v4.tests.full.CaseTests$Leaf@fe67d8d2
Leaf(2) = org.modelica.v4.tests.full.CaseTests$Leaf@de2f8005
Pair(Leaf(1),Leaf(2)) = org.modelica.v4.tests.full.CaseTests$Pair@d8e41584 = (org.modelica.v4.tests.full.CaseTests$Leaf@fe67d8d2, org.modelica.v4.tests.full.CaseTests$Leaf@de2f8005)
Pair(Leaf(1),Pair(Leaf(1),Leaf(2))) = org.modelica.v4.tests.full.CaseTests$Pair@6a311526 = (org.modelica.v4.tests.full.CaseTests$Leaf@fe67d8d2, org.modelica.v4.tests.full.CaseTests$Pair@d8e41584)
left1 = org.modelica.v4.tests.full.CaseTests$Leaf@fe67d8d2
left2 = org.modelica.v4.tests.full.CaseTests$Leaf@fe67d8d2
left1.parent = Pair(Leaf(1),Pair(Leaf(1),Leaf(2)))
left2.parent = Pair(Leaf(1),Leaf(2))

我不明白的是(我怀疑这是因为我错过了 Scala/Java 中等价性的一些微妙之处,或者也许我只是误解了输出)是 left1 和 left2 如何看起来具有相同的地址(或者我误解了这一点),但是不同的 parent ?!

如果有人能纠正我的错误,我将不胜感激。谢谢。

附注- 我正在运行 Scala 2.9,以防万一。

最佳答案

left1left2 不是相同的对象。尝试println(left1 eq left2),它会打印 false。默认的 toString 方法调用 Integer.toHexString(hashCode),因此如果两个对象的哈希码你一定会得到相同的 id火柴。在这里确实如此,因为案例类自动获得了不错的 hashCodeequals 实现。

关于java - Scala 案例类构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6694112/

相关文章:

java - 请放心 json-schema-validator

scala - Play Framework 如何在请求中更新 session

具有特征的案例类的equals/hashCode的Scala语义

java - Apache Tomcat (8.5.13) 启动问题

java - 创建 AlertDialog 时代码中断。我想我有上下文错误......?

scala - 为什么 Shapeless 中的 _0 Nat 是一个类而不是一个对象?

java - 您如何运行 SecureSocial 演示?

ruby - 如何设置 ruby​​ murmur 哈希的种子值

java - 如何通过组合键的哈希码来计算 Pojo 的哈希码

java - 如何在获取Android后对List<Model>数据进行排序