在java中的Switch语句中使用Integer类型

时间:2014-10-01 10:13:57

标签: java switch-statement

我在java中为我的Android应用程序编写了一些简单的代码,我得到了这些错误。

case expressions must be constant expressions private static final Integer为常数

private static final Integer INVALID_USER = 901;
private static final Integer SENDING_FAILED = 902;
private static final  Integer OK = 903;
/*
 *
 *  And some more project related declaration...
 *
 */


        switch (responseCode){
            case INVALID_USER:

                    // logout
                    break;

            case SENDING_FAILED:

                    //resend request
                    break;

            case OK:
                    break;
        }

这是因为我使用Integer Type,然后我将类型更改为int并且问题已解决

我的问题是为什么我们不能使用Integer作为案例表达。 Docs says " A switch works with the byte, short, char, and int primitive data types. It 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"虽然变量是常数 我读过this question但没有得到任何东西

3 个答案:

答案 0 :(得分:3)

  

常量表达式 用作switch语句中的case标签(   §14.11)并且对转让转换具有特殊意义(   §5.2)和.....

Definition of Constant Expression §15.28

  

编译时常量表达式是表示值的表达式   原始类型字符串不会突然完成。

现在在上面的场景中,编译器正在寻找常量表达式,因为它应该在编译时知道编译器。如上所述,Integer实际上不是编译器的常量表达式。

答案 1 :(得分:2)

Docs行" Docs说:开关使用byte,short,char和int原始数据类型。它还适用于枚举类型(在枚举类型中讨论),String类,以及一些包含某些原始类型的特殊类:Character,Byte,Short和Integer"

switch(expressions used here)

而不是case声明。

您可以将基本类型intcase一起使用,然后将Integer.valueOf(your_int_value);用于Integer

答案 2 :(得分:-2)

java不允许将Object用于交换机。我们可以使用byte,int,char和枚举值作为switch表达式。在jdk1.7中我们可以使用String作为switch表达式。要为包装类对象执行此操作,您需要使用包装类

的valueOf方法
private static final Integer INVALID_USER = 901;
private static final Integer SENDING_FAILED = 902;
private static final  Integer OK = 903;
/*
 *
 *  And some more project related declaration...
 *
 */


        switch (responseCode){
            case INVALID_USER.valueOf():

                    // logout
                    break;

            case SENDING_FAILED.valueOf():

                    //resend request
                    break;

            case OK.valueOf():
                    break;
        }