java switch null,如何在switch中使用null

"在Java中,无法直接在switch语句中使用null值。解决方法是在switch之前先检查变量是否为null,如果为null则执行特定操作。如:`if(i == null) { doSomething0(); }
摘要由CSDN通过智能技术生成

Integer i = ...

switch (i){

case null:

doSomething0();

break;

}

In the code above I cant use null in switch case statement. How can I do this differently?

I can't use default because then I want to do something else.

解决方案

This is not possible with a switch statement in Java. Check for null before the switch:

if (i == null) {

doSomething0();

} else {

switch (i) {

case 1:

// ...

break;

}

}

You can't use arbitrary objects in switch statements*. The reason that the compiler doesn't complain about switch (i) where i is an Integer is because Java auto-unboxes the Integer to an int. As assylias already said, the unboxing will throw a NullPointerException when i is null.

* Since Java 7 you can use String in switch statements.

More about switch (including example with null variable) in Oracle Docs - Switch

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值