如何在开关中使用空值
2022-08-31 05:27:37
Integer i = ...
switch (i) {
case null:
doSomething0();
break;
}
在上面的代码中,我不能在 switch case 语句中使用 null。我怎样才能以不同的方式做到这一点?我不能使用,因为那样我想做别的事情。default
Integer i = ...
switch (i) {
case null:
doSomething0();
break;
}
在上面的代码中,我不能在 switch case 语句中使用 null。我怎样才能以不同的方式做到这一点?我不能使用,因为那样我想做别的事情。default
这在 Java 中的语句中是不可能的。检查之前 :switch
null
switch
if (i == null) {
doSomething0();
} else {
switch (i) {
case 1:
// ...
break;
}
}
不能在语句*中使用任意对象。编译器不抱怨 where is 是 的原因是 Java 自动将 的框解为 .正如 assylias 已经说过的那样,拆箱会抛出一个 when is 。switch
switch (i)
i
Integer
Integer
int
NullPointerException
i
null
*从Java 7开始,您可以在语句中使用。String
switch
有关 Oracle Docs 中的更多信息(包括带有空变量的示例) - Switchswitch
switch ((i != null) ? i : DEFAULT_VALUE) {
//...
}