get method of hashmap is not returning null

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

}

 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.

链接地址: http://www.djcxy.com/p/15124.html

上一篇: JOIN和INNER JOIN的区别

下一篇: get hashmap的方法不返回null