Re: Enum, switch, and a null
"Lew" <lew@lewscanon.com> wrote in message
news:f_udnRN6Rq-d-E7bnZ2dnUVZ_h_inZ2d@comcast.com...
Wojtek wrote:
switch ( expression-returning-null ) throws NPE
While the JLS should address this explicitly, consider that the history of
switch() is to switch off integral primitive types, which cannot have a
null value. Another hint comes from the fact that the case labels must be
constant expressions, and a "static final Integer" doesn't work as a case
value.
In fact, if the switch expression is, say, Integer, a null value also will
throw an NPE:
<sscce>
public class Switcheroo
{
public static void main(String[] args)
{
Integer sw = null;
switch ( sw )
{
case 0:
System.out.println( "zero" );
break;
default:
System.out.println( "not zero" );
break;
}
}
}
</sscce>
Which you and I would both expect, since we know that
Integer x;
switch(x) ...
is short for
Integer x;
switch (x.intValue()) ...
I wonder, then, is
Enum e;
switch(e)...
short for
Enum e;
switch (e.ordinal())...
(Checks...) Yes it is, which explains the NPE, but geez, that's fragile.
Change the order of the enum constants, forget to recompile the world, and
your switches do entirely the wrong thimg.