Using Integer in Switch Statement

后端 未结 6 1780
心在旅途
心在旅途 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:36

    Switch require constant expressions in the case statements or enum constants. A constant expression is:

    an expression denoting a value of primitive type or a String that does not complete abruptly

    So Integers don't qualify. In your case, you can either use an int or an enum (which would make sense if your IDs are known at compile time).

    The only place where you can use a boxed type (for example an Integer) is in the switch expression:

    switch(Integer.valueOf(1)) {
        case 1: //
    }
    
    0 讨论(0)
  • 2020-12-10 15:37

    In the code shown 'i' is an object pointer, not a constant expression.

    0 讨论(0)
  • 2020-12-10 15:38

    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.

    0 讨论(0)
  • 2020-12-10 15:45

    Now that java offers enums, we usually do it like this :

    public enum MyKey {
       i,
       j
    }
    
    ...
    
    switch(mObj.getId()){
        case i: //do something
        default: //do something default
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 15:53

    You must use a constant value in a switch statement.

    switch(mObj.getId()){
        case 5: //do something
        default: //do something default
    }
    
    0 讨论(0)
提交回复
热议问题