Integer i = ...
    
switch (i) {
    case null:
        doSomething0();
        break;    
}

在上面的代码中,我不能在switch case语句中使用null。我该怎么做呢?我不能用默认,因为我想做别的。


当前回答

switch (String.valueOf(value)){
    case "null":
    default: 
}

其他回答

想想SWITCH是如何工作的,

对于原语,我们知道NPE自动装箱可能会失败 但对于String或enum,它可能会调用equals方法,这显然需要一个LHS值来调用equals。 因此,如果没有方法可以在null上调用,switch不能处理null。

你不能。你可以在switch中使用基本类型(int, char, short, byte)和String(仅在java 7中使用字符串)。原语不能为空。 开关前检查i是否处于单独状态。

Java文档明确指出:

禁止使用null作为开关标签可以防止编写永远不能执行的代码。如果开关表达式是引用类型,例如盒装基元类型或enum,如果表达式在运行时求值为空,则会发生运行时错误。

在switch语句执行之前,必须验证是否为空。

if (i == null)

参见Switch语句

case null: // will never be executed, therefore disallowed.

带开关的模式匹配

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

switch ((i != null) ? i : DEFAULT_VALUE) {
        //...
}