java - int float 与 double 的转换偏好

标签 java casting overloading

这是我的代码,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/

相关文章:

java String, replaceall() 但保留原始字符串中的大小写

C# params object[] 奇怪的行为

java - 下面的Java代码是如何工作的?它是一种隐式类型转换吗?

python - 如何访问所有父类的属性?

python - 无法重载 python socket.send

java - 在 Android 中,一个应用程序在较低 API 级别出现编译错误的情况下是否可以顺利运行?

java - 是否有语法可以从另一个匿名内部类获取对匿名内部类的引用?

c++ - 基类到派生类的类型转换

java - Java 中的新功能 Lambda 重载

java - Dropwizard Rest API 的 JSON 正文开头处存在无效字符