Array of generic nodes Java

11,960

I think Node<T> should be static.

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:

nonstatic class

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

static class

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

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.

Share:
11,960
Eduan Bekker
Author by

Eduan Bekker

I am currently a second year BSc Computer Science student at the University of Pretoria. I have experiance in the following: Java C++ Delpi 7 Joomla

Updated on June 04, 2022

Comments

  • Eduan Bekker
    Eduan Bekker almost 2 years

    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];
    

    Gives the following compiler error:

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

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