【问题标题】:"Cannot instantiate the type..."“无法实例化类型......”
【发布时间】:2011-08-14 09:30:47
【问题描述】:

当我尝试运行这段代码时:

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;
        }
    }
}

我收到此错误:

线程“main”java.lang.Error 中的异常:未解决的编译问题:
    无法实例化类型队列
    在 TwoColor.main(TwoColor.java:8)

我不明白为什么我不能实例化这个类......这对我来说似乎是正确的......

【问题讨论】:

标签: java class queue


【解决方案1】:

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

Queue<T> q = new LinkedList<T>;

【讨论】:

    【解决方案2】:

    Queue 是一个接口,因此您不能直接启动它。由其实现类之一启动它。

    从文档中所有已知的实现类:

    • 抽象队列
    • ArrayBlockingQueue
    • ArrayDeque
    • ConcurrentLinkedQueue
    • 延迟队列
    • LinkedBlockingDeque
    • LinkedBlockingQueue
    • 链表
    • PriorityBlockingQueue
    • 优先队列
    • 同步队列

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        您正在尝试实例化一个接口,您需要提供您要使用的具体类,即Queue&lt;Edge&gt; theQueue = new LinkedBlockingQueue&lt;Edge&gt;();

        【讨论】:

          【解决方案5】:

          你可以使用

          Queue thequeue = new linkedlist();
          

          Queue thequeue = new Priorityqueue();
          

          原因:队列是一个接口。所以你只能实例化它的具体子类。

          【讨论】:

            【解决方案6】:

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

            因此,如果前面的答案对您没有帮助,请检查您import 是您实际要导入的类,而不是您的 IDE 可能提示您的具有相同名称的其他东西。

            例如,如果您尝试从自己编写的 myCollections 包中实例化类 Queue:

            import java.util.*; // replace this line
            import myCollections.Queue; // by this line
            
                 Queue<Edge> theQueue = new Queue<Edge>();
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-12-30
              • 2019-07-26
              • 2013-09-27
              • 2015-04-30
              • 1970-01-01
              • 2021-03-12
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多