问题描述
Java varargs实现中似乎存在一个错误。当方法使用不同类型的vararg参数重载时,Java无法区分合适的类型。
There seems to be a bug in the Java varargs implementation. Java can't distinguish the appropriate type when a method is overloaded with different types of vararg parameters.
它给出了一个错误方法.. 。对于类型不明确...
请考虑以下代码:
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");
}
}
说:一般来说,你不应该超载varargs方法,否则它将是程序员很难弄清楚哪些重载被调用。
the docs say: "Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called."
然而他们没有提到这个错误,并且不是程序员发现它很难,而是编译器。
however they don't mention this error, and it's not the programmers that are finding it difficult, it's the compiler.
想法?
编辑 - 编译:Sun jdk 1.6.0 u18
EDIT - Compiler: Sun jdk 1.6.0 u18
推荐答案
关于。
那里没有真正的解决方案,只是辞职。
No real resolution there, just resignation.
Varargs(和自动拳击,这也导致难以理解的行为,尤其是与varargs结合使用)已经在Java的生命中被拴住了,这是一个领域它显示了。所以它在规范中比在编译器中更容易出错。
Varargs (and auto-boxing, which also leads to hard-to-follow behaviour, especially in combination with varargs) have been bolted on later in Java's life, and this is one area where it shows. So it is more a bug in the spec, than in the compiler.
至少,它会产生好的(?)SCJP技巧问题。
At least, it makes for good(?) SCJP trick questions.
这篇关于varargs和重载的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!