问题
I have a question about objects in a switch statement.
I am aware that variables used in case clause must be final (otherwise we get: "case expressions must be constant expressions").
Final on objects means only reference can't be changed, the value still can be changed by other non final reference therefore, we cant use objects in 'case'.
But why cant we use wrappers? They are immutable arent they?
java code:
Integer i = 8;
final int x = 10;
switch ( x )
{
case x:
System.out.println("x");
break;
case i:
System.out.println("i");
break;
}
回答1:
Your variable i is a reference to an Integer object.
The Integer object is immutable.
The variable i itself is a mutable reference to an object. It's not a constant variable, which must be final and be of primitive type or type String.
EDIT: Finally found the references in the Java Language Specification.
First, a switch label can include either an enum or a constant expression, per 14.11: The switch statement
SwitchLabel:
case ConstantExpression :
case EnumConstantName :
default :
A constant expression is well defined in 15.28: Constant expressions. The relevant item in this case is:
Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
Constant variables are defined by 4.12.4: final variables
A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).
回答2:
Wrappers are allowed, but you should use switch-case to differentiate between values of a variable, not between variables themselves, i.e.
Integer i = 8;
final int x = 10;
switch ( i )
{
case (10):
System.out.println("x");
break;
case (8):
System.out.println("i");
break;
}
This doesnt make much sense though, but it should be possible and hopefully explains the usage to you.
来源:https://stackoverflow.com/questions/26850261/wrappers-in-switch-statement