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(...)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…