Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

java - 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(...)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change your constant to primitive type:

private static final int i = 1;

and you'll be fine. switch can only work with primitives, enum values and (since Java 7) strings. Few tips:

  • new Integer(myint).equals(...) might be superflous. If at least one of the variables is primitive, just do: myint == .... equals() is only needed when comparing to Integer wrappers.

  • Prefer Integer.valueOf(myInt) instead of new Integer(myInt) - and rely on autoboxing whenever possible.

  • Constant are typically written using capital case in Java, so static final int I = 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...