2013-10-20 72 views
2

我正在實現一個併發的循環隊列,這個隊列使用在隊列頭部和尾部使用單獨的鎖 的數組。隊列中的每個節點如下所示:通用節點陣列Java

private class Node<T> 
    { 
     public T item; 
     ReentrantLock lock = new ReentrantLock(); 
     Node(){} 
     void lock() {lock.lock();} 
     void unlock() {lock.unlock();} 
    } 

我無法在隊列類的構造函數中創建隊列。

public Queue(int capacity) { 
    items = (Node[]) new Object[capacity];//This line gives the problem 
    head = size = 0; 
    } 

我已經找到了解決辦法here,但是這個代碼:

@SuppressWarnings("unchecked") 
    Node<T>[] slots = (Node<T>[]) new Node<?>[capacity]; 

提供了以下編譯器錯誤:

Cannot create a generic array of Queue<T>.Node<?> 

我的問題是什麼是初始化數組的正確方法通用對象?

+2

也許這個問題幫助:http://stackoverflow.com/questions/2927391/whats-the-reason-i-cant-create-generic-array-types-in-java – andreih

+1

po可以複製[如何:泛型數組創建](http://stackoverflow.com/questions/529085/how-to-generic-array-creation),請參閱接受的答案。 – 2013-10-20 14:28:46

回答

3

我認爲Node<T>應該是靜態的。

private static class Node<T> 
{ 
    public T item; 
    ReentrantLock lock = new ReentrantLock(); 

    void lock() {lock.lock();} 
    void unlock() {lock.unlock();} 
} 

... 

@SuppressWarnings("unchecked") 
Node<T>[] slots = (Node<T>[]) new Node<?>[capacity]; 

一般來說,我們有兩種選擇:

非靜態類

public class Queue2<T> { 

    public Queue2(int capacity) { 

     Queue2<T>.Node2[] slots2 = new Queue2.Node2[capacity];  
    } 


    private class Node2 
    { 
     private T item; 
     ReentrantLock lock = new ReentrantLock(); 

     public Node2(Object object) {} 
     void lock() {lock.lock();} 
     void unlock() {lock.unlock();} 
    } 
} 

靜態類

public class Queue<T> { 

    public Queue(int capacity) { 

     Queue.Node<T>[] slots = (Node<T>[]) new Node<?>[capacity]; 
    } 

    private static class Node<T> 
    { 
     public T item; 
     ReentrantLock lock = new ReentrantLock(); 

     void lock() {lock.lock();} 
     void unlock() {lock.unlock();} 
    } 
} 

你會參考節點類中的第一個例子爲Queue2<T>.Node,而您將第二個示例中的節點類別稱爲Queue.Node<T>

Of the two alternatives showed here, the second is preferable. Nested classes that are not static are implemented by including a reference to the enclosing instance, since they may, in general, access components of that instance. Static nested classes are usually both simpler and more efficient.

+0

謝謝。使其靜態工作。 –

0

還有兩種其他方法可以進行編譯。

  1. Node一個公共類

  2. 保持Node作爲一個私人的,非靜態,類,然後從實例中刪除通配符:

    Node<T>[] slots = (Node<T>[]) new Node[capacity];