什么是 Java 中的“歧义类型”错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20255420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is an 'ambiguous type' error in Java?
提问by user2671186
In the following code, I get an error from the compiler on the last line that says: 'the type List is Ambiguous' (on the line that attempts to define cgxHist list). What am I doing wrong?
在下面的代码中,我从编译器的最后一行收到一条错误消息:“列表类型不明确”(在尝试定义 cgxHist 列表的行上)。我究竟做错了什么?
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class drawr extends JPanel{
public static int animationSpeed=470;
public static int diameter = 50;
hBod allHBods[];
List<String> cgxHist = new ArrayList<String>();
I actually wanted the list to contain integers, but when I try to 'cast' the list as such, by replacing <String>with <int>, the error on that line becomes 'Syntax error on token "int", Dimensions expected after this token'. Advice please.
我实际上希望列表包含整数,但是当我尝试将列表“转换”为这样时,通过替换<String>为<int>,该行上的错误变为“标记“int”上的语法错误,此标记后预期的尺寸”。请指教。
回答by Jeroen Vannevel
java.awt.List
java.util.List
Both of these exist. You'll have to add the namespace in front to use one:
这两个都存在。您必须在前面添加命名空间才能使用一个:
java.util.List<String> cgxHist = new ArrayList<String>();
If you don't, it doesn't know how to interpret the List<T>: is it the awtone or util? Ergo: ambiguous.
如果你不这样做,它不知道如何解释List<T>:是awt一个还是util?故:暧昧。
回答by Blub
The problem is that there is a Listclass in both the java.awtand the java.utilpackage, and as you are importing all classes in those packages, the compiler doesn't know which one you mean.
问题在于包和包List中都有一个类,当您导入这些包中的所有类时,编译器不知道您指的是哪个类。java.awtjava.util
So you should either not use the asterisk to import all classes at the same time (just import the ones you actually need) or instead of Listwrite java.util.List<String> cgxHist = new ArrayList<String>();
因此,您不应该使用星号同时导入所有类(只需导入您实际需要的类),或者不要List编写java.util.List<String> cgxHist = new ArrayList<String>();

