【问题标题】:Method Overloading with varargs使用可变参数重载方法
【发布时间】:2015-08-31 13:04:08
【问题描述】:

我对这个话题有点困惑,原因在这段代码中:

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");
    }
}

这段代码的输出是“字节”,原因是选择了最具体的类型,因为byteshortint中最具体的类型是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");
    }
}

输出是“整数”,我不知道为什么?我知道在算术指令byteshort 被隐式提升为int 的情况下,但在这里我们调用一个值在byteshort 范围内的方法,那么该方法如何使用int 参数被调用?

另外,如果我用int 参数注释掉方法,那么代码会显示找不到合适方法的错误。为什么???

【问题讨论】:

    标签: java int byte variadic-functions short


    【解决方案1】:

    14 是整数文字。所以调用了int... 版本。

    没有 byteshort 文字,但如果您要调用 Numbers((byte)2, (byte)3);,则将调用 byte... 版本。

    【讨论】:

    • Numbers() 没有被报告为模棱两可的事实,显然它仍然应该让我感到害怕
    • @Clashsoft 但它并不模棱两可。有明确的适用规则。完全不同的事情是,使用这样的原始值进行重载是否是个好主意,但这是程序员的错。
    • "你可以给我byteshortint。你什么都不给我。这意味着你给了我byte。"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    相关资源
    最近更新 更多