尽管密钥已经存在,但Scala HashMap.contains()返回false

时间:2017-12-01 17:02:17

标签: java scala hashmap

我使用可变的Scala Map,如果一个键已经存在,则使用contains()进行检查。

在一个实例中,它返回false,尽管密钥(具有相同的hashCode(),在调试器中验证它)已经存在。 使用Java的默认序列化方法对映射中的对象进行反序列化。

我敢打赌它与序列化/反序列化有某种关系,因为没有它,我没有问题。

我可以采取哪些其他步骤来找到根本原因?

HashMap中

 private val knowledgeRecords = collection.mutable.Map[Entity, KnowledgeRecord]().empty

测试密钥是否已存在:

if (knowledgeRecords.contains(entity))

实体的HashCode函数

override def hashCode(): Int = {
if (id == null)
  0
else
  id.hashCode

} }

实体的相同功能

  def canEqual(other: Any): Boolean = other.isInstanceOf[Entity]

  override def equals(other: Any): Boolean = other match {
   case that: Entity =>
    (that canEqual this) && id == that.id
   case _ => false

}

Id在Entity

的构造函数中定义
class Entity(var id: String)

编辑:如果我在消毒后打电话

val cloneValuesOfMap = knowledgeRecords.values.toList
knowledgeRecords.clear()
cloneValuesOfMap.foreach(item=>knowledgeRecords.put(item.entity, item))

然后contains()有效。我不知道为什么。

我调试了包含函数的litte。 在HashTable中有函数

private[this] def findEntry0(key: A, h: Int): Entry = {
var e = table(h).asInstanceOf[Entry]
while (e != null && !elemEquals(e.key, key)) e = e.next
e

密钥位于存储桶表(0)中。但是在'反序列化'用例中,使用h = 2调用此函数,因此e变为null。

0 个答案:

没有答案