What is an 'ambiguous type' error in Java?

2020-04-04 18:44发布

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?

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.

2条回答
Summer. ? 凉城
2楼-- · 2020-04-04 19:19
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 awt one or util? Ergo: ambiguous.

查看更多
做自己的国王
3楼-- · 2020-04-04 19:20

The problem is that there is a List class in both the java.awt and the java.util package, and as you are importing all classes in those packages, the compiler doesn't know which one you mean.

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 List write java.util.List<String> cgxHist = new ArrayList<String>();

查看更多
登录 后发表回答