gpt4 book ai didi

java - 为什么编译器会给出模棱两可的方法调用错误?

转载 作者:行者123 更新时间:2023-11-29 06:33:27 26 4
gpt4 key购买 nike

这是一个代码片段。

class BoxVar{

static void call(Integer... i){
System.out.println("hi"+i);
}
static void call(int... i ){
System.out.println("hello"+i);
}
public static void main(String... args){
call(10);
}
}

程序编译正常。当我运行程序时,它给了我

java: reference to call is ambiguous, both method call(java.lang.Integer...) in com.exams.BoxVar and method call(int...) in com.exams.BoxVar match

有人能解释一下原因吗?

最重要的是,我尝试将第一种方法转换为类似这样的方法。

 static void call(Long... i){
System.out.println("hi"+i);
}

运行良好。有人可以帮我解决这个问题吗?谢谢。

最佳答案

编译器准确地告诉你发生了什么。 Integerint 类型在概念上是相同的。因此,这两个方法签名是相同的。

假设编译成功,编译器应该调用哪个方法?

类型 LongInteger 不一样(换句话说,编译器将整数类型视为两种不同的类型),这就是它编译成功的原因:

int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.

参见 Integral Types作为引用。

关于java - 为什么编译器会给出模棱两可的方法调用错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26577530/

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