java三元运算符用的多不多,使用Java三元运算符时的奇怪行为

When I write my java code like this:

Map map = new HashMap<>()

Long number =null;

if(map == null)

number = (long) 0;

else

number = map.get("non-existent key");

the app runs as expected but when I do this:

Map map = new HashMap<>();

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

I get a NullPointerException on the second line. The debug pointer jumps from the second line to this method in the java.lang.Thread class:

/**

* Dispatch an uncaught exception to the handler. This method is

* intended to be called only by the JVM.

*/

private void dispatchUncaughtException(Throwable e) {

getUncaughtExceptionHandler().uncaughtException(this, e);

}

What is happening here? Both these code paths are exactly equivalent isn't it?

Edit

I am using Java 1.7 U25

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值