【发布时间】:2019-01-09 20:48:13
【问题描述】:
关于方法签名中的 var-args 的类似问题被问了几次(1,2),但有一个极端情况我不明白。编译器可以区分int...和long...重载的方法签名,并调用较小类型的方法。
然而byte 和char 的大小显然不一样,但编译器抱怨test() 下面的方法不明确:
static void test(byte... v) { System.out.println("Byte"); }
static void test(char... v) { System.out.println("Char"); }
public static void main(String[] args) {
test(); // Error:(7, 5) java: reference to test is ambiguous
// both method test(byte...) in App and method test(char...) in App match
}
short... 和 char... 也是如此,但 int... 和 char... 并不模棱两可。
为什么 char... 与 byte... 或 short... 被认为是模棱两可的,而 byte... 和 short... 在方法签名中是可区分的?
static void test(byte... v) { System.out.println("Byte"); }
static void test(short... v) { System.out.println("Short"); }
public static void main(String[] args) {
test(); // Byte
}
【问题讨论】:
-
在您的示例中,您没有将参数传递给测试。编译器不知道你打算调用哪一个,因为它通常会从你传递给它的参数中推断出来。
-
int 可以隐式转换为 long,而 byte 和 char 彼此不兼容。主要是因为char和byte都是8位的,而char是无符号的。
-
@SotrisDelimanolis 如果您认为这是重复的,请指出答案,解释为什么
char...不同。 -
stackoverflow.com/a/32293611/438154 byte 和 char 之间没有“更具体”的关系,而 int 和 char 之间有。
-
@Powerlord
char是 16 位无符号整数,而不是 8 位。
标签: java