Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get method of hashmap is not returning null

Tags:

scala

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)
    }
  }

}
like image 707
blue-sky Avatar asked Aug 02 '13 10:08

blue-sky


People also ask

Can HashMap get return null?

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.

Does HashMap return null key not found?

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.

Does map return null Java?

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.

What does map get return if not found?

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.


2 Answers

 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);
like image 97
Mohsin Shaikh Avatar answered Oct 13 '22 07:10

Mohsin Shaikh


In Scala, Int is the AnyVal type(kind of primitive). It cannot be null.

like image 1
rocketboy Avatar answered Oct 13 '22 06:10

rocketboy