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(...)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With