Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Integer in Switch Statement

For various business reasons I want to hold some static IDs in one of my classes. They were originally int but I wanted to change them to Integer so I could do an equals on them (ie MY_ID.equals(..) which avoids NPEs)

When I change them to Integer I get errors in my switch statement. The docs say that Integer should be ok within Switches.

To quote

[Switch] also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

In my code below if i is a int then it compiles. When it is an Integer it doesnt saying that a constant expression is required. I have tried doing .intValue() but this doesnt work either.

Am I being really stupid? Or completely misreading the docs?

private static final Integer i = 1;

@Test
public void test() {
    switch(mObj.getId()){
        case i: //do something
        default: //do something default
    }

}

Thanks for any pointers here. For the time being I am keeping them as int and doing new Integer(myint).equals(...)

like image 809
RNJ Avatar asked Sep 26 '12 14:09

RNJ


1 Answers

because I was looking at this...

The accepted answer says that:

switch can only work with primitives, enum values and (since Java 7) strings

However,

14.11 The switch Statement

outlines the JavaSE7 documentation for switch that shows:

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.

I just wanted to clarify for future surfers.

like image 154
artisancreek Avatar answered Sep 28 '22 16:09

artisancreek