3

There is an error in the code saying cannot create a generic array of E. Could anyone help me in this thanks

    **Q = new E[N];**

Here is the full code;

package org.circular;

public class CircularArrayQueue<E> implements QueueADT<E> {

private static final int capacity = 5;
private E[] Q;
private final int N; // capacity
private int f = 0;
private int r = 0;

public CircularArrayQueue() {
    this(capacity);
}

public CircularArrayQueue(int capacity) {
    N = capacity;
    Q = new E[N];
}

public int size() {
    if (r > f)
        return r - f;
    return N - f + r;
}

public boolean isEmpty() {
    return (r == f) ? true : false;
}

public boolean isFull() {
    int diff = r - f;
    if (diff == -1 || diff == (N - 1))
        return true;
    return false;
}

public void enqueue(E element) throws FullQueueException {
    if (isFull()) {
        throw new FullQueueException("Full");
    } else {
        Q[r] = element;
        r = (r + 1) % N;
    }
}

public E dequeue() throws EmptyQueueException {
    E item;
    if (isEmpty()) {
        throw new EmptyQueueException("Empty");
    } else {
        item = Q[f];
        Q[f] = null;
        f = (f + 1) % N;
    }
    return item;
}

@Override
public E front() throws EmptyQueueException {
    if (isEmpty()) {
        throw new EmptyQueueException("Empty");

    }
    return null;
}

}
jpw
  • 42,772
  • 6
  • 57
  • 78

2 Answers2

2

The error is that, in Java, it is illegal to create a new instance of a non-reifiable type. A non-reifiable type is one which exists at compile time but does not exist at run time.

Generics in Java are implemented by erasure, which is to say that all the generic type parameters are erased by the compiler during compilation. The generic type information, therefore, does not exist at runtime. For this reason, creating a generic array is not allowed because the compiler cannot guarantee that at run-time all the operations on the array will be type safe. Therefore, the compiler raises an error.

The following non-reifiable types cannot be created as arrays by Java (E is a generic type parameter):

  • E[]
  • List<E>[]
  • List<String>[]

You can cast an array to a generic type and the program will compile ... however in place of an error you will get a warning about an unchecked cast. Again, the type information does not exist at run-time so the warning is alerting you that your code may not be type safe.

You may be able to circumvent your problem by using List<E> in place of E[N]. Arrays and generics mix poorly because in Java arrays are covariant (enabling arrays to know their component type at run-time) whereas generic collections are invariant (generic type information does not exist at run-time; the compiler enforces type safety).

scottb
  • 9,181
  • 3
  • 38
  • 49
0

Java does not allow for the creation of generic arrays. You will have to cast it

Q = new (E[]) Object[N];
anguyen
  • 457
  • 4
  • 17