Integer i = ... switch (i) { case null: doSomething0(); break; }
在上面的代码中,我不能在 switch case 语句中使用 null。我怎样才能做到这一点?我不能使用default,因为那时我想做其他事情。
default
switch这对于 Java 中的语句是不可能的。null之前检查switch:
switch
null
if (i == null) { doSomething0(); } else { switch (i) { case 1: // ... break; } }
您不能在switch语句*中使用任意对象。编译器不抱怨switch (i)where iis anInteger的原因是因为 Java 自动拆箱Integer到int. 正如 assylias 已经说过的,拆箱会抛出NullPointerExceptionwhen iis null。
switch (i)
i
Integer
int
NullPointerException
*从 Java 7 开始,您可以使用Stringinswitch语句。
String
Oracle Docs - Switch中有关switch(包括带有空变量的示例)的更多信息