如何在switch中使用null [英] How to use null in switch
问题描述
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开始,你可以在
* 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屋!