case expressions must be constant expression

今天使用swith语句时,调用定义好的常量时,编译报错:case expressions must be constant expression。html

常量类以下:java

public class Constants{
    public static final Integer HIGH=5;
    
     public static final Integer MEDIUM=3;
     
      public static final Integer LOW=1;
}

调用以下:express

switch(level){
    case Constants.HIGH:
    ……
    
    case Constants.MEDIUM:
    ……
    case Constants.LOW:
    ……
}

后来查了下,有人说定义常量时,常量要是static final.这个个人定义里已是了,但仍然报错,最后仍是查到一个英文的答案,说是要使用基本数据类型,不能使用包装类,即其only be applied to primitives and Strings,因此改为以下定义:app

public class Constants{
    public static final int HIGH=5;
    
     public static final int MEDIUM=3;
     
      public static final int LOW=1;
}

至此问题解决。ide

附:参考答案:http://www.coderanch.com/t/329474/java/java/final-static-Integer-considered-constant this

Yes. Case statements can only take compile-time constants, or enums, and the definition of compile-time constant expressions can only be applied to primitives and Strings. That's just the way they wrote the rules. On the one hand, yes the compiler has access to enough information here that it could probably figure out how to use an int rather than an Integer here. On the other hand, there's really no reason this number needs to be an Integer in the first place, is there? It can easily be changed to an int, and everything will work fine.spa

相关文章
相关标签/搜索