在java重载中发现含糊不清且没有合适的方法的错误

在java重载中发现含糊不清且没有合适的方法的错误,java,Java,假设我有一个重载类,如下所示 class Test{ public void m1(int a,float b){ System.out.println("hello"); } public void m1(float a,int b){ System.out.println("hai"); } public static void main(String[] args){ Test t = new Tes

假设我有一个重载类,如下所示

class Test{
    public void m1(int a,float b){
        System.out.println("hello");
    }
    public void m1(float a,int b){
        System.out.println("hai"); 
    }
    public static void main(String[] args){
        Test t = new Test();
        t.m1(10,10);//error
        t.m1(10.5f,10.6f);//error
    }
}
当我使用两个int值调用
m1()
方法时,比如
m1(10,10)
错误是

 error: reference to m1 is ambiguous, both method m1(int,float) in Test and method m1(float,int) in Test match
t.m1(10,10);
 ^
当我调用带有两个浮点值的
m1()
方法时,比如
m1(10.5f,10.6f)
错误

error: no suitable method found for m1(float,float)
t.m1(10.5f,10.6f);
 ^
method Test.m1(float,int) is not applicable
  (actual argument float cannot be converted to int by method invocation conversion)
method Test.m1(int,float) is not applicable
  (actual argument float cannot be converted to int by method invocation conversion)

有人能解释一下为什么这个程序显示两种不同类型的错误吗

当您试图将
int
参数传递给需要
float
的方法时,该参数可以通过自动转换从
int
转换为
float
(加宽原语转换不会丢失有关数值整体大小的信息)。因此,您的两个方法都可以执行调用
t.m1(10,10)
,编译器无法在这两个方法之间进行选择(因为这两个方法都需要将一个参数从
int
转换为
float
,因此对于给定的参数,这两个方法中没有一个比另一个更合适)。因此,
对m1的引用不明确
错误


当您将
float
参数传递给需要
int
的方法时,如果不显式转换为
int
,则无法将该参数转换为
int
,因为
float
被截断为
int
时会丢失精度。因此,您的任何方法都不能执行
t.m1(10.5f,10.6f)

我想知道您为什么期望相等的错误?当
int
是导致数据丢失的“较低”数据类型时,编译器应该如何将
float
提升为
int
?我认为在方法区域编译器没有找到我调用的方法,所以我认为两个方法调用都没有合适的方法错误,为什么您认为这两个方法都不合适,当您使用
int
?“从int转换为float而不丢失数据”来调用它们时,通常(对于所有int),这是不正确的。@Matthias您是对的。我不准确。我来编辑。