相关疑难解决方法(0)

为什么带签名(primitive,wrapper)和(primitive,primitive)的两个方法会导致方法调用(包装器,原语)不明确?

这只是一个练习,但我无法弄清楚这种模糊性:

private static void flipFlop(String str, int i, Integer iRef) {
System.out.println(str + "ciao");
}

private static void flipFlop(String str, int i, int j) {
System.out.println(str + "hello");
}

public static void main(String[] args) {
flipFlop("hello", new Integer(4), 2004);
}
Run Code Online (Sandbox Code Playgroud)

它说:

对于类型Test,方法flipFlop(String,int,Integer)是不明确的

我猜想第二个参数将被解包为int,所以第二个flipFlop方法就是选择.

java jdk1.6

17
推荐指数
2
解决办法
1060
查看次数

为什么这不会产生歧义?

我刚刚写了一些具有以下结构的代码:

public void method(int x) {
    //...
}

public void method(int x, String... things) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

我很惊讶这编译了,如果我调用的话

method(3);
Run Code Online (Sandbox Code Playgroud)

然后它会选择第一个.显然,这在某种意义上是自然选择的,但如果第一种方法不存在,这将是调用第二种方法的合理方式(使用空的varargs数组).所以它应该被认为是模糊的并产生编译时错误?

或者这被视为特例?

这样对待它似乎是错误的,因为这意味着添加新方法可能会破坏现有代码,这不是一个非常幸福的事态.

(Goodness只知道如果第一个被添加为包含第二个子类的子类的新方法,你最终会调用哪个...)

java overloading javac variadic-functions ambiguous-call

6
推荐指数
1
解决办法
120
查看次数

为什么默认为“int”,而不是“byte”?

请解释一下,为什么当我编写 4 个重载方法并调用它时 => 它选择以“int”为默认值的方法,而不是“byte”,后者更接近/更好,因为它可以存储从 -127 到 128 的值?

class Main {
    public static void method(short s) {
        System.out.println("short");
    }

    public static void method(byte b) {
        System.out.println("byte");
    }

    public static void method(int i) {
        System.out.println("int");
    }

    public static void method(long l) {
        System.out.println("long");
    }

    public static void main(String[] args) {
        // put your code here
        method(10);
    }
}
Run Code Online (Sandbox Code Playgroud)

java int byte overloading

0
推荐指数
1
解决办法
81
查看次数