Integer i = ...
switch (i) {
case null:
doSomething0();
break;
}
在上面的代码中,我不能在switch case语句中使用null。我该怎么做呢?我不能用默认,因为我想做别的。
Integer i = ...
switch (i) {
case null:
doSomething0();
break;
}
在上面的代码中,我不能在switch case语句中使用null。我该怎么做呢?我不能用默认,因为我想做别的。
当前回答
你必须做出一个
if (i == null) {
doSomething0();
} else {
switch (i) {
}
}
其他回答
你必须做出一个
if (i == null) {
doSomething0();
} else {
switch (i) {
}
}
这在Java 18之前是不可能用switch语句实现的。在切换之前必须检查是否为空。但是现在,有了模式匹配,这些都成为过去式了。看看JEP 420:
模式匹配和空 传统上,switch语句和表达式会抛出 如果选择器表达式的结果为null,则为NullPointerException null测试必须在开关外部完成:
static void testFooBar(String s) {
if (s == null) {
System.out.println("oops!");
return;
}
switch (s) {
case "Foo", "Bar" -> System.out.println("Great");
default -> System.out.println("Ok");
}
}
当switch只支持少数参考类型时,这是合理的。 然而,if switch允许任何类型的选择器表达式和大小写 标签可以有类型模式,这样独立的空测试才有感觉 就像一个武断的区分,并引起不必要的样板文件和 犯错的机会。最好是集成空测试 进入开关:
static void testFooBar(String s) {
switch (s) {
case null -> System.out.println("Oops");
case "Foo", "Bar" -> System.out.println("Great");
default -> System.out.println("Ok");
}
}
更多关于开关(包括空变量的例子)在Oracle Docs - switch
带开关的模式匹配
switch语句的null行为将随着模式匹配的加入而改变(在JDK 17/18/19/20中有预览状态)
Switches and null Traditionally, switch statements and expressions throw NullPointerException if the selector expression evaluates to null, so testing for null must be done outside of the switch. [...] This was reasonable when switch supported only a few reference types. However, if switch allows a selector expression of any type, and case labels can have type patterns, then the standalone null test feels like an arbitrary distinction, and invites needless boilerplate and opportunity for error. It would be better to integrate the null test into the switch by allowing a new null case label.
参见JEP 433:模式匹配开关(第四预览)
这意味着基本上你可以简单地写
switch (null) {
case null: ...
}
但如果省略大小写null:-part,开关仍然会抛出NullPointerException
我今天才知道,你不必放另一层缩进/花括号,只是因为if检查为空。你可以做以下任何一种:
if (i == null) {
// ...
} else switch (i) {
case 1:
// ...
break;
default:
// ...
}
or
if (i != null) switch (i) {
case 1:
// ...
break;
default:
// ...
} else {
// ...
}
switch(i)如果i为null,将抛出NullPointerException,因为它将尝试将Integer拆箱为int。所以case null,恰好是非法的,永远不会被达到。
你需要在switch语句之前检查i是否为空。