Tuesday, 27 August 2013

Java: Weird method ambiguity

Java: Weird method ambiguity

Consider the following code:
public class Converter {
public <K> MyContainer<K> pack(K key, Object[] values) {
return new MyContainer<>(key);
}
public MyContainer<IntWrapper> pack(int key, Object[] values) {
return new MyContainer<>(new IntWrapper(key));
}
public static final class MyContainer<T> {
public MyContainer(T object) { }
}
public static final class IntWrapper {
public IntWrapper(int i) { }
}
public static void main(String[] args) {
Converter converter = new Converter();
MyContainer<IntWrapper> test = converter.pack(1, new
String[]{"Test", "Test2"});
}
}
The above code compiles without problems. However, if one changes Object[]
to Object... in both pack signatures and new String[]{"Test", "Test2"} to
"Test", "Test2", the compiler complains about the call to converter.pack
being ambiguous.
Now, I can understand why it could be considered ambiguous (as int can be
autoboxed into an Integer, thus matching the conditions, or lack thereof,
of K). However, what I can't understand is why the ambiguity isn't there
if you're using Object[] instead of Object....
Can someone please explain this odd behavior?

No comments:

Post a Comment