“Cannot instantiate the type…”

2019-01-25 02:08发布

When I try to run this code:

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

I get this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Cannot instantiate the type Queue
    at TwoColor.main(TwoColor.java:8)

I don't understand why I can't instantiate the class... It seems right to me...

标签: java class queue
5条回答
【Aperson】
2楼-- · 2019-01-25 02:56

java.util.Queue is an interface so you cannot instantiate it directly. You can instantiate a concrete subclass, such as LinkedList:

Queue<T> q = new LinkedList<T>;
查看更多
够拽才男人
3楼-- · 2019-01-25 03:02

You can use

Queue thequeue = new linkedlist();

or

Queue thequeue = new Priorityqueue();

Reason: Queue is an interface. So you can instantiate only its concrete subclass.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-25 03:06

You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();.

查看更多
看我几分像从前
5楼-- · 2019-01-25 03:08

Queue is an Interface not a class.

查看更多
SAY GOODBYE
6楼-- · 2019-01-25 03:13

Queue is an Interface so you can not initiate it directly. Initiate it by one of its implementing classes.

From the docs all known implementing classes:

  • AbstractQueue
  • ArrayBlockingQueue
  • ArrayDeque
  • ConcurrentLinkedQueue
  • DelayQueue
  • LinkedBlockingDeque
  • LinkedBlockingQueue
  • LinkedList
  • PriorityBlockingQueue
  • PriorityQueue
  • SynchronousQueue

You can use any of above based on your requirement to initiate a Queue object.

查看更多
登录 后发表回答