switch 语句中的包装器 [英] Wrappers in switch statement

查看:70
本文介绍了switch 语句中的包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 switch 语句中的对象的问题.我知道 case 子句中使用的变量必须是最终的(否则我们会得到:case 表达式必须是常量表达式").对象上的 final 意味着只能更改引用,其他非最终引用仍然可以更改该值,因此,我们不能在 'case' 中使用对象.
但是为什么我们不能使用包装器呢?它们是不可变的,不是吗?

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代码:

    Integer i = 8;
    final int x = 10;

    switch ( x )
    {
    case x:
        System.out.println("x");
        break;
    case i:             
        System.out.println("i");
        break;
    }

推荐答案

您的变量 i 是对 Integer 对象的引用.

Your variable i is a reference to an Integer object.

Integer 对象是不可变的.

The Integer object is immutable.

变量i 本身是一个对对象的可变引用.它不是一个常量变量,它必须是最终的并且是原始类型或字符串类型.

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.

终于在 Java 语言规范中找到了参考资料.

Finally found the references in the Java Language Specification.

首先,开关标签可以包含枚举或常量表达式,根据 14.11:switch语句

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 :

常量表达式在 15.28:常量表达式.这种情况下的相关项目是:

A constant expression is well defined in 15.28: Constant expressions. The relevant item in this case is:

引用常量变量的简单名称(第 6.5.6.1 节)(第 4.12.4 节).

Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).

常量变量由 4.12.4:最终变量

常量变量是使用常量表达式(第 15.28 节)初始化的原始类型或字符串类型的最终变量.

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).

这篇关于switch 语句中的包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆