java在编译方法重载,Java编译错误:结合了重载的方法参考

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> 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 or any other object.

Thanks in advance

Dimitri

解决方案

Well, we can simplify this:

// takes a Runnable

public static void doStuff(Runnable runable) {

System.out.println("Runnable");

}

// takes a Callable

public static void doStuff(Callable> callable) {

System.out.println("Callable");

}

And two extra methods that are overloads.

private static List go() {

return null;

}

private static List go(int i) {

return null;

}

What do you think will happen if you call this:

doStuff(YourClass::go);

Yeah... this will fail to match. And you might think that this is stupid as it only makes sense that go is the one that takes no arguments, it is easy for you in this simple situation to make this judgment, it's not for the compiler. In essence this is like a dead-lock:

In order to know which doStuff method to call, we need to know which go to call; and at the same time to understand which go to call we need to know which doStuff to call, or:

we need to resolve the method in order to find the target type, but we need to know the target type in order to resolve the method.

Same thing happens in your case with ArrayList having more than one constructors...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值