有没有一种方法可以解决模棱两可的方法调用而无需强制转换? [英] Is there a way to work around Ambiguous method call without casting?

查看:215
本文介绍了有没有一种方法可以解决模棱两可的方法调用而无需强制转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public static void main(String[] args) throws Exception {
    test(new LinkedList());
}

public static void test(Queue qeueue){
    System.out.println("Queue");
}

public static void test(List list){
    System.out.println("List");
}

InteliJ不允许我运行该项目.

InteliJ is not letting me run the project.

  1. 有什么办法可以解决此问题?
  2. 如果两者的特异性相同,那么JVM将使用这两个中的哪个?是随机的吗?

我已经阅读了相关的SO q/a,但是没有人给出如何围绕它进行编译的答案. 他们只列出了原因,例如歧义方法调用intelliJ 15

I have read related SO q/a but no one gives an answer how to compile around it. They just list the reason, e.g. Ambiguous method call intelliJ 15

一个更讨厌的例子是:

test(null);

我一直在阅读非常有趣的文章: http: //javabypatel.blogspot.be/2016/05/ambiguous-method-overloading.html

I have been reading the article that is quite interesting: http://javabypatel.blogspot.be/2016/05/ambiguous-method-overloading.html

推荐答案

一个LinkedList既是List又是Deque,而Deque又是Queue.

A LinkedList both a List and a Deque, which in turn is a Queue.

test方法的调用因此对于编译器是模棱两可的,因为无法确定要调用的重载.

The test method invocation is therefore ambiguous to the compiler, as there is no way to figure which overload to invoke.

要么合并方法以接受唯一对象(例如,Collection),要么显式转换为任一目标类型(或完全具有不同的方法名称).

Either merge the methods to accept a unique object (e.g. a Collection), or explicitly cast to either target type (or, have different method names altogether).

还请记住:不鼓励使用原始类型,您可能希望对通用集合进行参数化.

Also remember: it is discouraged to use raw types, you probably want to parametrize your generic collections.

这篇关于有没有一种方法可以解决模棱两可的方法调用而无需强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆