HashMap Scale:java.util.NoSuchElementException

问题描述 投票:0回答:1

回答!我试图将问题归结为以下代码和输出。简短说明:如果在hashMap中找不到密钥,我们打印出不同的等式概念:==,equals,eq,最后是hashCode和hashMap.contains(key)的重复。它是一个单线程应用程序!

val hashMap : collection.immutable.HashMap[State,State] = transition
val key : State = currentState
if (! hashMap.contains(key))
   hashMap.keySet.map { entry : State =>
      if (entry.ID == key.ID) {
        println("================================")
        println("entry.ID is " + entry.ID)
        println("entry == key is " + (entry == key))
        println("entry.equals(key) is " + entry.equals(key))
        println("entry eq key is " + entry.eq(key))
        println("entry.hashCode == key.hashCode is " + (entry.hashCode == key.hashCode))
        println("hashMap.contains(key) is " + hashMap.contains(key))
        System.exit(0)
      }
    }
else
  println(s"""Key "${key.ID}" found""")

在程序执行期间重复执行代码,产生输出:

Key "Start" found
Key "Start" found
Key "Start" found
================================
entry.ID is Start
entry == key is true
entry.equals(key) is true
entry eq key is true
entry.hashCode == key.hashCode is true
hashMap.contains(key) is false  

我不明白这是怎么可能的。我甚至可以证明hashMap.keySet包含hashMap中没有包含的元素,我认为这些元素不一致。请注意,'key'是扩展ArrayBuffer的对象(不是类)的实例,其'equals'函数已被覆盖以在ID上进行比较。但是,据我所知,这应该不重要,因为等于功能很重要。非常感谢帮助。

编辑:状态和开始的定义:

abstract class State(val ID:String) extends ArrayBuffer[Result] {
  override def canEqual(that: Any): Boolean = that.isInstanceOf[State]
  override def equals(that: Any): Boolean = that match {
    case that:State => ID == that.ID
    case _ => false
  }
}

object START extends State("Start"){}
scala hashmap singleton
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.