gpt4 book ai didi

java - 数字文字的自动装箱 : wrapper initialization vs passing method arguments inconsistency

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:28:06 28 4
gpt4 key购买 nike

请考虑两种情况:

//1
Short s = 10; //obviously compiles

//2
takeShort(10); //error - int is not applicable

//where:
static void takeShort(Short s) {}

我假设情况 1 被编译器更改为:

short _temp_s = 10;
Short s = Short.valueOf(_temp_s);

您能否解释一下编译器在情况 2 中试图做什么,所以它无法编译?如果它不像案例 1 那样尝试应用自动装箱,那么为什么?

编辑

johnchen902 答案中对 JSL 的引用解释了编译器的行为。

仍然不完全清楚为什么 JLS 不支持方法调用转换的“缩小原始转换,然后是装箱转换”,就像它在 byte、short、char 或 int 类型的常量表达式的赋值转换中所做的那样。有什么想法吗?

最佳答案

Short s = 10;

这是一个赋值转换10是一个常量表达式。 JLS说:

5.2. Assignment Conversion

Assignment conversion occurs when the value of an expression is assigned to a variable: the type of the expression must be converted to the type of the variable.

......

In addition, if the expression is a constant expression of type byte, short, char, or int:

  • A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:
    • Short and the value of the constant expression is representable in the type short.

takeShort(10);

这是一个方法调用转换JLS说:

5.3. Method Invocation Conversion

Method invocation conversion is applied to each argument value in a method or constructor invocation : the type of the argument expression must be converted to the type of the corresponding parameter.

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

  • an identity conversion
  • a widening primitive conversion
  • a widening reference conversion
  • a boxing conversion optionally followed by widening reference conversion
  • an unboxing conversion optionally followed by a widening primitive conversion.

......

If the type of the expression cannot be converted to the type of the parameter by a conversion permitted in a method invocation context, then a compile-time error occurs.

与赋值转换不同,上面列出的转换不能将int转换为Short,因此会出现编译时错误。

不幸的是有些人在我批准之前拒绝了 kiruwka 的编辑,所以我自己编辑

方法调用转换示例:

// takeInteger(int) takeDouble(double) takeObject(Object) takeIntegerObject(Integer)

takeInteger(5); // an identity conversion
takeDouble(5); // a widening primitive conversion
takeObject(new Integer(5)); // a widening reference conversion
takeIntegerObject(5); // a boxing conversion
takeObject(5); // a boxing conversion followed by widening reference conversion
takeInteger(new Integer(5)); // an unboxing conversion
takeDouble(new Integer(5)); // an unboxing conversion followed by a widening primitive conversion.

关于java - 数字文字的自动装箱 : wrapper initialization vs passing method arguments inconsistency,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16505959/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com