This line : var counter : Integer = jm.get(ls)
in below code returns an Integer of value 0 when it should be null. Why is this occuring ?
According to the documentation the get method of HashMap returns null if the element is not found. The code below is counting the number of elements in a list
import scala.collection.JavaConversions._
object Tester {
def main(args: Array[String]) {
var listOfLinks : java.util.Set[String] = new java.util.TreeSet[String]
listOfLinks.add("1")
listOfLinks.add("1")
listOfLinks.add("1")
listOfLinks.add("2")
listOfLinks.add("3")
listOfLinks.add("3")
listOfLinks.add("3")
listOfLinks.add("3")
var l: java.util.List[String] = new java.util.ArrayList[String]
var jm: java.util.Map[String, Int] = new java.util.HashMap[String, Int];
for (ls <- listOfLinks) {
var counter : Integer = jm.get(ls)
if (counter == null) {
jm.put(ls, 1)
} else {
counter = counter + 1
jm.put(ls, counter)
}
}
for(jmv <- jm){
println(jmv._1+" , "+jmv._2)
}
}
}
HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Returns null if the HashMap contains no mapping for this key. A return value of null does not necessarily indicate that the HashMap contains no mapping for the key; it's also possible that the HashMap explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.
Indeed, if a Java Map implementation allows for null values, then it is possible for the Map to return its value for the given key, but that value might be a null. Often this doesn't matter, but if it does, one can use Map. containsKey() to determine if the Map entry has a key entry.
Map get() method If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.
var jm: java.util.Map[String, Int] = new java.util.HashMap[String, Int];
Here in the Map interface you are using key as String the value is Int. So Int default value is the 0.
var counter : Integer = jm.get(ls)
So here counter can hold only 0 value because in the counter variable value come not Key.
jm.get(ls);
In Scala, Int
is the AnyVal
type(kind of primitive). It cannot be null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With