Java &引用;无法实例化类型…”;

Java &引用;无法实例化类型…”;,java,class,queue,Java,Class,Queue,当我尝试运行此代码时: 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 v

当我尝试运行此代码时:

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;
        }
    }
}
import java.io.*;
导入java.util.*;
公共类双色
{
公共静态void main(字符串[]args)
{
Queue theQueue=新队列();
}
公共阶级边缘
{
//u和v是构成此边的顶点。
私人国际大学;
私人INTV;
//构造函数方法
公共边缘(int-newu,int-newv)
{
u=新u;
v=新v;
}
}
}
我得到这个错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot instantiate the type Queue at TwoColor.main(TwoColor.java:8) 线程“main”java.lang中出现异常。错误:未解决的编译问题: 无法实例化队列类型 位于TwoColor.main(TwoColor.java:8)
我不明白为什么我不能实例化这个类。。。对我来说这似乎是对的…

队列是一个接口而不是一个类。

java.util.Queue
是一个接口,所以不能直接实例化它。您可以实例化一个具体的子类,例如
LinkedList

Queue<T> q = new LinkedList<T>;
Queue q=newlinkedlist;
是一个接口,因此您不能直接启动它。通过它的一个实现类初始化它

从文档中可以看到所有已知的实现类:

  • 抽象队列
  • 阵列锁定队列
  • 阿莱德克
  • ConcurrentLinkedQueue
  • 延迟队列
  • LinkedBlockingDeque
  • LinkedBlockingQueue
  • 链接列表
  • 优先阻塞队列
  • 优先队列
  • 同步队列

您可以根据需要使用上述任何一种方法来启动队列对象。

如果您试图实例化一个接口,则需要给出要使用的具体类,即
Queue theQueue=new LinkedBlockingQueue()

您可以使用

Queue thequeue = new linkedlist();


原因:队列是一个接口。因此,您只能实例化它的具体子类。

我也遇到了同样的问题,无法实例化一个类的类型,而我完全确定它不是抽象的。原来我是从
Java.util
实现一个抽象类,而不是实现我自己的类

因此,如果前面的答案对您没有帮助,请检查您是否导入了实际要导入的类,而不是IDE可能提示您的同名类

例如,如果您试图从自己编写的包myCollections中实例化类队列:

import java.util.*; // replace this line
import myCollections.Queue; // by this line

     Queue<Edge> theQueue = new Queue<Edge>();
import java.util.*;//更换这条线
导入myCollections.Queue;//按这条线
Queue theQueue=新队列();
import java.util.*; // replace this line
import myCollections.Queue; // by this line

     Queue<Edge> theQueue = new Queue<Edge>();