如何在switch中使用null [英] How to use null in switch

查看:709
本文介绍了如何在switch中使用null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Integer i = ...

switch (i){
    case null:
        doSomething0();
        break;    
    }

在上面的代码中,我不能在switch case语句中使用null。我怎么能这样做?
我不能使用默认因为那时我想做别的事情。

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.

推荐答案

使用Java中的 switch 语句是不可能的。在开关之前检查 null

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

你不能在<$ c中使用任意对象$ c>切换语句 * 。编译器没有抱怨 switch(i)的原因 i 整数是因为Java将 Integer 自动取消装箱到 int 。正如assylias所说,当 i null NullPointerException c $ c>。

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.

* 从Java 7开始,你可以在 String code>切换语句。

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

更多关于切换(包括示例null变量)在 Oracle Docs - Switch

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

这篇关于如何在switch中使用null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆