Using scala, 2.8:
import scala.collection.mutable
import mutable.MultiMap
val m = new mutable.HashMap[String, mutable.Set[String]] with MultiMap[String, String]
m.addBinding("key", null)
m exists { _._2 contains null }
prints false
m exists { _._2 isEmpty }
prints false
m("key").size
prints 1
How do I find the first key (or any) key that was added via an addBinding call with a value of null?
In Scala 2.7.7, you get a NullPointer straight away when adding null:
Using Scala 2.8.0.RC7, that is no longer the case. However, as Randall has observed, the behaviour is not entirely consistent either:
Most of the work when adding an entry is done in
FlatHashTable
When you add an entery,
addEntryis invoked, which looks like this:null.asInstanceOf[AnyRef]just gives you backnull, and theelemHashCode(elem)returns zero if the elem isnull. So in this case, the element with index zero is 'initialized' withnull(which is the value it already had), but the tableSize is increased. This explains the results that are seen in the REPL.If you call
headon the Set, ultimately the iterator inFlatHashTableis called, as can be seen from the stacktrace. This is implemented as follows:hasNextwill return false, since the element that we stored in the Array is null, therefore, the call tonextwill call Iterator.empty.next, which throws an exception.Since adding null to a HashSet is not handled consistently in Scala 2.8, this indeed looks like a bug. Also, as already has been remarked, it provides another good reason to stay away from using null where possible.
Edit Since I couldn't find a ticket for this, I added it.