当我尝试运行此代码时:
import java.io.*;
import java.util.*;
public class TwoColor
{
public static void main(String[] args)
{
Queue<Edge> theQueue = new Queue<Edge>();
}
public class Edge
{
//u and v are the vertices that make up this edge.
private int u;
private int v;
//Constructor method
public Edge(int newu, int newv)
{
u = newu;
v = newv;
}
}
}
我收到此错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot instantiate the type Queue at TwoColor.main(TwoColor.java:8)
我不明白为什么我不能实例化这个课......对我来说似乎是对的......
答案 0 :(得分:44)
java.util.Queue
是一个接口,因此您无法直接实例化它。您可以实例化一个具体的子类,例如LinkedList
:
Queue<T> q = new LinkedList<T>;
答案 1 :(得分:26)
Queue是一个接口,因此您无法直接启动它。由其中一个实现类启动它。
从文档中所有已知的实现类:
您可以根据您的要求使用上述任何一项来启动队列对象。
答案 2 :(得分:4)
队列是一个接口而不是一个类。
答案 3 :(得分:3)
您正在尝试实例化一个接口,您需要提供您想要使用的具体类,即Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();
。
答案 4 :(得分:3)
您可以使用
Queue thequeue = new linkedlist();
或
Queue thequeue = new Priorityqueue();
原因:队列是一个界面。所以你只能实例化它的具体子类。
答案 5 :(得分:0)
我遇到了同样的问题,无法实例化我绝对确定不是抽象的类的类型。原来我是从 Java.util
实现一个抽象类,而不是实现我自己的类。
因此,如果之前的答案对您没有帮助,请检查您是否import
是您实际想要导入的类,而不是 IDE 可能暗示您的同名类。
例如,如果您尝试从自己编写的包 myCollections 中实例化类 Queue :
import java.util.*; // replace this line
import myCollections.Queue; // by this line
Queue<Edge> theQueue = new Queue<Edge>();