Weird behaviour when using Java ternary operator

后端 未结 3 2328
误落风尘
误落风尘 2021-02-19 20:49

When I write my java code like this:

Map map = new HashMap<>()
Long number =null;
if(map == null)
    number = (long) 0;
else
    numbe         


        
3条回答
  •  Happy的楠姐
    2021-02-19 21:52

    They are not equivalent.

    The type of this expression

    (map == null) ? (long)0 : map.get("non-existent key");
    

    is long because the true result has type long.

    The reason this expression is of type long is from section §15.25 of the JLS:

    If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

    When you lookup a non-existant key the map returns null. So, Java is attempting to unbox it to a long. But it's null. So it can't and you get a NullPointerException. You can fix this by saying:

    Long number = (map == null) ? (Long)0L : map.get("non-existent key");
    

    and then you'll be okay.

    However, here,

    if(map == null)
        number = (long) 0;
    else
        number = map.get("non-existent key");
    

    since number is declared as Long, that unboxing to a long never occurs.

提交回复
热议问题