Java通用节点数组 [英] Array of generic nodes Java

查看:58
本文介绍了Java通用节点数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据一个数组实现一个并发循环队列,该数组利用了队列开头和结尾处的单独锁
。队列中的每个节点如下所示:

I am implementing a concurrent circular Queue in terms of an array that makes use of separate locks at the head and the tail of the queue. Each node in the queue looks as follows:

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

我无法在队列类的构造函数中创建队列。

I cannot create the queue in the constructor of the queue class.

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

我找到了一个解决方案此处,但此代码为:

I have found a solution here, but this code:

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

给出以下编译器错误:

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

我的问题是初始化通用对象数组的正确方法是什么?

My question is what is the correct way to initialize an array of generic objects?

推荐答案

我认为 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];

通常,我们有两个选择:

Generally we have two options:

非静态类

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>

You would refer to the node class in the first example as Queue2<T>.Node, whereas you would refer to the node class in the second example as 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.

这篇关于Java通用节点数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆