Eclipse bug?什么时候短短不短? [英] Eclipse bug? When is a short not a short?

查看:151
本文介绍了Eclipse bug?什么时候短短不短?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Eclipse中的一个错误吗?

Is this a bug in Eclipse?

当声明一个简短的变量时,编译器将整数文字视为一个简写。

When declaring a short variable the compiler treats the the integer literal as a short.

// This works
short five = 5;

然而,当传递整数文字作为短参数时,它不会做同样的事情,而是生成编译错误:

Yet it does not do the same when passing integer literals as short parameters, instead a compilation error is generated:

// The method aMethod(short) in the type Test is not applicable for 
// the arguments (int)
aMethod(5); 

它清楚地知道一个整数字面量在一个简短的范围之外:

It clearly knows when an integer literal is outside the range of a short:

// Type mismatch: cannot convert from int to short
    short notShort = 655254

-

class Test {
    void aMethod(short shortParameter) {
    }

    public static void main(String[] args) {
        // The method aMethod(short) in the type Test is not applicable for 
        // the arguments (int)
        aMethod(5); 

      // the integer literal has to be explicity cast to a short
      aMethod((short)5);

      // Yet here the compiler knows to convert the integer literal to a short
      short five = 5;
      aMethod(five);


      // And knows the range of a short
      // Type mismatch: cannot convert from int to short
        short notShort = 655254
    }
}

参考: Java基本数据类型

推荐答案

p>这是因为当调用一个方法时,只有原始的扩展转换被授权,而不是原始的缩小转换(int - > short)。这是在 JLS#5.3

It's because when invoking a method, only primitive widening conversions are authorised, not primitive narrowing conversions (which int -> short is). This is defined in the JLS #5.3:


方法调用上下文允许使用以下之一:

Method invocation contexts allow the use of one of the following:


  • 一个身份转换(§5.1.1)

  • 扩展原始转换(§5.1.2)

  • 扩大引用转换(§5.1.5)

  • 一个拳击转换(§5.1.7),随后可以加宽引用转换

  • 一个取消装箱转换(§5.1.8)可选,然后扩大原始转换。

  • an identity conversion (§5.1.1)
  • a widening primitive conversion (§5.1.2)
  • a widening reference conversion (§5.1.5)
  • a boxing conversion (§5.1.7) optionally followed by widening reference conversion
  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

另一方面在分配的情况下,允许缩小转换,前提是该数字是一个常数,并且适合短时间,cf JLS#5.2

On the other hand, in the case of an assignment, narrowing conversion is allowed, provided that the number is a constant and fits within a short, cf JLS #5.2:


狭窄的原始对决如果变量的类型为byte,short或char,则可以使用版本,并且常量表达式的值可在变量的类型中表示。

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

这篇关于Eclipse bug?什么时候短短不短?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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