How to use null in switch

前端 未结 12 1090
南方客
南方客 2020-12-04 10:17
Integer i = ...

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

In the code above I cant use null in switch case state

12条回答
  •  爱一瞬间的悲伤
    2020-12-04 11:17

    switch(i) will throw a NullPointerException if i is null, because it will try to unbox the Integer into an int. So case null, which happens to be illegal, would never have been reached anyway.

    You need to check that i is not null before the switch statement.

提交回复
热议问题