Integer i = ...
switch (i){
case null:
doSomething0();
break;
}
在上面的代码中,我不能在switch case语句中使用null。我怎样才能以不同的方式做到这一点呢?我不能使用default
,因为我想做其他的事情。
发布于 2015-06-03 00:04:21
switch ((i != null) ? i : DEFAULT_VALUE) {
//...
}
发布于 2012-04-26 19:06:21
如果I为null
,switch(i)
将抛出NullPointerException,因为它将尝试将Integer
拆箱为int
。因此,碰巧是非法的case null
,无论如何都不会被联系到。
您需要在switch
语句之前检查i是否不为null。
发布于 2012-04-26 19:14:49
Java文档清楚地指出:
禁止使用null作为开关标签可以防止编写永远无法执行的代码。如果开关表达式是引用类型,如装箱的基元类型或枚举,则如果表达式在运行时计算为null,则会发生运行时错误。
在执行Swithch语句之前,必须验证是否为null。
if (i == null)
case null: // will never be executed, therefore disallowed.
https://stackoverflow.com/questions/10332132
复制相似问题