相关疑难解决方法(0)

varargs和重载的错误?

Java varargs实现中似乎存在一个错误.当方法使用不同类型的vararg参数重载时,Java无法区分适当的类型.

它给了我一个错误 The method ... is ambiguous for the type ...

请考虑以下代码:

public class Test
{
    public static void main(String[] args) throws Throwable
    {
        doit(new int[]{1, 2}); // <- no problem
        doit(new double[]{1.2, 2.2}); // <- no problem
        doit(1.2f, 2.2f); // <- no problem
        doit(1.2d, 2.2d); // <- no problem
        doit(1, 2); // <- The method doit(double[]) is ambiguous for the type Test
    }

    public static void doit(double... ds)
    {
        System.out.println("doubles");
    }

    public static void doit(int... is)
    {
        System.out.println("ints"); …
Run Code Online (Sandbox Code Playgroud)

java overloading variadic-functions

21
推荐指数
2
解决办法
3856
查看次数

使用原始类型和包装类的varargs重载时为什么会出现模糊错误?

我不明白为什么在这里的情况1,它没有给出编译错误,相反在情况2(varargs),它给出了编译错误.任何人都可以详细说明编译器在这两种情况下的差异吗?我经历过很多关于它的帖子,但还不能理解它.

情况1

public class Test {

    public void display(int a) {
        System.out.println("1");
    }

    public void display(Integer a) {
        System.out.println("2");
    }

    public static void main(String[] args) {
        new Test().display(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出为: 1

案例#2

public class Test {

    public void display(int... a) {
        System.out.println("1");
    }

    public void display(Integer... a) {
        System.out.println("2");
    }

    public static void main(String[] args) {
        new Test().display(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

The method display(int[]) is ambiguous for the type Test
Run Code Online (Sandbox Code Playgroud)

java primitive overloading variadic-functions wrapper

7
推荐指数
1
解决办法
481
查看次数

方法重载中的不明确问题

有人可以帮助解释为什么测试 2 和测试 3 有问题吗?

public static void main (String[] args) {
    byte b = 5;
    doCalc(b, b);
}
Run Code Online (Sandbox Code Playgroud)

测试1:这两种方法没有歧义问题。

static void doCalc(byte a, byte b) {
    System.out.print("byte, byte");
}
static void doCalc(Byte s1, Byte s2) {
    System.out.print("Byte, Byte");
}
Run Code Online (Sandbox Code Playgroud)

测试2:这两个方法没有编译时二义性,但存在运行时二义性。

static void doCalc(Byte... a) {
    System.out.print("byte 1...");
}
static void doCalc(long... a) {
    System.out.print("byte 2...");
}
Run Code Online (Sandbox Code Playgroud)

测试3:这两个方法在编译时存在二义性。

static void doCalc(Byte... a) {
    System.out.print("byte 1...");
}
static void doCalc(byte... a) {
    System.out.print("byte 2...");
}
Run Code Online (Sandbox Code Playgroud)

java

5
推荐指数
1
解决办法
161
查看次数