How to use null in switch

前端 未结 12 1132
南方客
南方客 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:06

    Just consider how the SWITCH might work,

    • in case of primitives we know it can fail with NPE for auto-boxing
    • but for String or enum, it might be invoking equals method, which obviously needs a LHS value on which equals is being invoked. So, given no method can be invoked on a null, switch cant handle null.

提交回复
热议问题