在java中的Switch语句中使用Integer类型
我在java中为我的Android应用程序编写了一些简单的代码,我得到了这些错误。
I was writing some simple code in java for my android app and i got these errors.
case表达式必须是常量表达式
,而 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;
}
这是因为我使用了整数类型
,然后我将类型更改为 int
并解决问题
This is because i used Integer Type
, then i changed type to int
and problem is solved
我的问题是为什么我们无法使用 Integer
作为案例表达式。 文档说交换机使用byte,short,char和int原始数据类型。它也适用于枚举类型(在枚举类型中讨论),String类,以及一些包含某些原始类型的特殊类:字符,字节,短整数和整数虽然变量是常量
我读过这个问题,但没有得到任何东西
My question is why we cant use Integer
as a case expression. 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" though variable is constant
I read this question but didnt get any thing
常量表达式 用作switch语句中的case标签($ b $b§14.11)并对转让转换具有特殊意义($ b $b§5.2)和.....
Constant expressions are used as case labels in switch statements ( §14.11 ) and have a special significance for assignment conversion ( §5.2 ) and .....
编译时常量表达式是表示原语的
值的表达式键入或字符串但不会突然完成。
A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly.
现在进入上面的场景编译器正在寻找常量表达式,因为它应该在编译时知道编译器。如上所述 Integer
实际上不是一个常量表达式对于编译器。
Now in above scenario compiler is looking for constant expression as it should be know to the compiler at the compile time.As stated Integer
is actually not a constant Expression for the compiler.