【问题标题】:Java - short and castingJava - 短和强制转换
【发布时间】:2011-02-12 19:49:32
【问题描述】:

我有以下代码sn-p。

public static void main(String[] args) {
 short a = 4;
 short b = 5;
 short c = 5 + 4;
 short d = a;
 short e = a + b; // does not compile (expression treated as int)


 short z = 32767;
 short z_ = 32768; // does not compile (out of range)

 test(a);
 test(7); // does not compile (not applicable for arg int)
}

public static void test(short x) { }

以下总结是否正确(仅关于上面使用short的示例)?

  • 没有强制转换的直接初始化只能使用文字或单个变量(只要值在声明类型的范围内)
  • 如果赋值的 rhs 处理使用变量的表达式,则必须进行强制转换

但是考虑到前面的摘要,为什么我需要转换第二个方法调用的参数呢?

【问题讨论】:

标签: java casting primitive-types


【解决方案1】:

short 值进行算术运算的结果始终为inttest(7) 不起作用,因为您没有说 7 是 short 类型。编译器在这里应该更聪明一点。

【讨论】:

  • 所以你是说当函数被调用时,一些算术运算被应用于文字参数 7?
  • 不,test(7) 中没有算术。 a+b 是带有 int 结果的算术运算,test(7) 是带有 int 字面量作为参数的方法调用。
【解决方案2】:

调用test(7); 中的“7”是int,不会自动转换为short

它在您声明和初始化 short 值时起作用,但这是编译器的特殊情况。方法调用不存在这种特殊情况。

【讨论】:

    【解决方案3】:

    这些是相关的 JLS 部分:

    JLS 5.1.1 Identity Conversion

    任何类型都允许从一个类型转换为同一类型。

    JLS 5.2 Assignment Conversion

    赋值转换发生在将表达式的值赋给变量时:必须将表达式的类型转换为变量的类型。赋值上下文允许使用以下之一:

    • 身份转换
    • [...]

    另外,如果表达式是byteshortcharint类型的常量表达式:

    • 如果变量的类型是byteshortchar,并且常量表达式的值可以用变量的类型表示,则可以使用缩小原语转换。

    以上规则解释了以下所有内容:

    short a = 4;     // representable constant
    short b = 5;     // representable constant
    short c = 5 + 4; // representable constant
    short d = a;     // identity conversion
    short e = a + b; // DOES NOT COMPILE! Result of addition is int
    
    short z  = 32767; // representable constant
    short z_ = 32768; // DOES NOT COMPILE! Unrepresentable constant
    

    至于为什么不能编译:

    test(7); // DOES NOT COMPILE! There's no test(int) method!
    

    这是因为带常量的窄化转换只为赋值定义;不适用于方法调用,其规则完全不同。

    JLS 5.3. Method Invocation Conversion

    方法调用转换特别不包括整数常量的隐式缩小,这是赋值转换的一部分。 Java 编程语言的设计者认为,包含这些隐式缩小转换会给重载方法匹配解析过程增加额外的复杂性。

    我将仅引用 Effective Java 2nd Edition,第 41 条:明智地使用重载:

    决定选择哪种重载的规则极其复杂。它们在语言规范中占据了三十三页页,很少有程序员能理解它们的所有细微之处。


    另见

    【讨论】:

    • 感谢您的所有回答!这对我帮助很大!
    猜你喜欢
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多