我对这个主题有点困惑,原因在这段代码中:
public class File
{
public static void main(String[] args)
{
numbers();
}
static void numbers(int...x)
{
System.out.println("Integers");
}
static void numbers(byte...x)
{
System.out.println("Byte");
}
static void numbers(short...x)
{
System.out.println("Short");
}
}
此代码的输出是“Byte”,原因是选择了最具体的类型,因为在 byte
、short
和 int
中code> 最具体的类型是 byte
,这就是选择它的原因。
但是如果我将代码修改为-
public class File
{
public static void main(String[] args)
{
numbers(1, 4);
}
static void numbers(int...x)
{
System.out.println("Integers");
}
static void numbers(byte...x)
{
System.out.println("Byte");
}
static void numbers(short...x)
{
System.out.println("Short");
}
}
输出是“整数”,我无法弄清楚为什么?我知道在算术指令中 byte
和 short
会隐式提升为 int
,但在这里我们调用一个方法,其值在byte
和 short
的范围,那么如何调用带有 int
参数的方法呢?
而且,如果我用 int
参数注释掉该方法,则代码会显示找不到合适方法的错误。为什么???
最佳答案
1
和 4
是整数文字。因此调用了 int...
版本。
没有 byte
或 short
文字,但如果您要调用 Numbers((byte)2, (byte)3);
将调用 byte...
版本。
关于java - 使用可变参数重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32311970/