2011-04-28 88 views
24

當我嘗試運行此代碼:「無法實例的類型......」

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)

我不明白爲什麼我不能實例班...看起來對我來說......

+1

可能重複的[無法實例化類型列表](http://stackoverflow.com/questions/7960149/cannot-instantiate-the-type-listproduct) – Raedwald 2014-07-17 12:12:06

回答

43

java.util.Queue是一個接口,所以你不能直接實例化它。您可以實例化一個具體的子類,如LinkedList

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

啊,謝謝!! – StickFigs 2011-04-28 04:46:00

4

排隊是接口不是一個類。

25

Queue是一個接口,所以你不能直接啓動它。由其實施類之一啓動它。

從文檔的所有已知實現類:

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

您可以使用根據您的需要來啓動隊列對象的任何以上。

3

你正試圖實例化一個接口,你需要給你想要使用的具體類,即Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();

3

您可以使用

Queue thequeue = new linkedlist(); 

Queue thequeue = new Priorityqueue(); 

原因:隊列是一個接口。所以你可以只實例化它的具體子類。