Using Integer in Switch Statement

后端 未结 6 1795
心在旅途
心在旅途 2020-12-10 15:05

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 s

6条回答
  •  星月不相逢
    2020-12-10 15:52

    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.

提交回复
热议问题