gpt4 book ai didi

java - int float 与 double 的转换偏好

转载 作者:行者123 更新时间:2023-12-01 17:57:28 26 4
gpt4 key购买 nike

这是我的代码,java中的简单重载代码。

public class Test {
static void test(float x){
System.out.print("float");
}

static void test(double x){
System.out.print("double");
}

public static void main(String[] args){
test(99.9);
test(99.9f);
test(99);
}
}

答案是

double
float
float

我知道为什么它在第一次和第二次调用时给出答案,但在第三次调用时它调用 float 。为什么?如果您有,请通过一些知识链接分享答案。

最佳答案

JLS §15.12.2.5. Choosing the Most Specific Method指定选择最合适方法的规则。相关部分是(我用粗体突出显示):

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

A type S is more specific than a type T for any expression if S <: T (§4.10).

JLS §4.10.1. Subtyping among Primitive Types定义:

The following rules define the direct supertype relation among the primitive types:

  • double >1 float
  • float >1 long
  • long >1 int
  • int >1 char
  • int >1 short
  • short >1 byte

或者将它们串联起来,忽略 char最右侧是最具体的:

double > float > long > int > short > byte

因此,如您所见,一个 int值,甚至是 long值,会选择float double 上的参数参数,但如 JLS §5.1.2. Widening Primitive Conversion说:

A widening primitive conversion from int to float, or from long to float, or from long to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value.

关于java - int float 与 double 的转换偏好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43556542/

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