I use a mutuable Scala Map and check with contains() if a key already exists.
In one instance it returns false, although the key (with the same hashCode(), verified it in the debugger) already exists. The objects in the map are deserialized by using Java's default serialization method.
My bet is that it's somehow related to the serialization/deserialization, since without it, I don't have the issue.
What further steps can I do, to find the root cause ?
HashMap
private val knowledgeRecords = collection.mutable.Map[Entity, KnowledgeRecord]().empty
Test if key already exists:
if (knowledgeRecords.contains(entity))
HashCode function of Entity
override def hashCode(): Int = {
if (id == null)
0
else
id.hashCode
} }
equal functions of Entity
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 is defined in the constructor of Entity
class Entity(var id: String)
Edit: If I call after the deserilization
val cloneValuesOfMap = knowledgeRecords.values.toList
knowledgeRecords.clear()
cloneValuesOfMap.foreach(item=>knowledgeRecords.put(item.entity, item))
then contains() works. I don't know why.
I've debugged a litte the contains function. In HashTable there is the function
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
The keys are in the bucket table(0). But in the 'deserialization' usecase this function is called with h = 2, thus e gets null.