Java autoboxing and ternary operator madness

后端 未结 4 828
感动是毒
感动是毒 2020-11-30 07:41

Just spent a frustrating couple of hours debugging this code:

    LinkedHashMap rsrqs = new LinkedHashMap();
           


        
4条回答
  •  盖世英雄少女心
    2020-11-30 08:20

    1
    

    is an int, not an Integer. So, Java is going to un-box your Integer to int, which causes the NullPointerException. When you auto-unbox a null Integer, it results in a NullPointerException. ( reference here )

    But when you use

     Integer.valueOf(-1) 
    

    it doesn't need to auto-unbox it, which leads to no exceptions.

提交回复
热议问题