java switch null,如何在switch中使用null
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 cant 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 cant use arbitrary objects in switch statements*. The reason that the compiler doesnt 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
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 cant 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 cant use arbitrary objects in switch statements*. The reason that the compiler doesnt 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