I have the following class with an overloaded method:
import java.util.ArrayList;
import java.util.concurrent.Callable;
public abstract class Test {
public void test1 () {
doStuff (ArrayList::new); // compilation error
}
public void test2 () {
doStuff ( () -> new ArrayList<> ());
}
public abstract void doStuff (Runnable runable);
public abstract void doStuff (Callable<ArrayList<String>> callable);
}
The method test1
results in a compilation error with the error message
The method doStuff(Runnable) is ambiguous for the type Test
.
I've added a third method test3
which looks like this:
public void test3 () {
doStuff ( () -> {
new ArrayList<> ();
});
}
Here the method doStuff(Runnable)
is executed which is obvious.
But how does the compiler decide which of the two methods is executed in test2
?
Why can I use the lambda expression but not the method reference?
The lambda expression in test2
useses the method which returns the callable, why does the method reference try to use the other method?
This seems to me like a java bug.
Edit:
It has nothing to do with the ArrayList
and/or the generic type of it. Same error when you have Callable<String>
or any other object.
Thanks in advance
Dimitri