2013-10-20 43 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];