25

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...

StickFigs
  • 253
  • 1
  • 3
  • 4
  • 1
    possible duplicate of [Cannot instantiate the type List](http://stackoverflow.com/questions/7960149/cannot-instantiate-the-type-listproduct) – Raedwald Jul 17 '14 at 12:12

6 Answers6

45

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>;
Cameron Skinner
  • 51,692
  • 2
  • 65
  • 86
27

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.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
4

Queue is an Interface not a class.

Andrew Lazarus
  • 18,205
  • 3
  • 35
  • 53
3

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.

Robin Ellerkmann
  • 2,083
  • 4
  • 29
  • 34
Amit Anand
  • 33
  • 4
3

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>();.

Jugal Shah
  • 3,621
  • 1
  • 24
  • 35
0

I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util instead of implementing my own class.

So if the previous answers did not help you, please check that you import the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.

For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :

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

     Queue<Edge> theQueue = new Queue<Edge>();
Badda
  • 1,329
  • 2
  • 15
  • 40