2013-11-03 72 views
3

有一个在代码说法不能创建E. 的通用阵列任何人都可以帮助我在此感谢圆阵队列错误

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

以下是完整的代码中的错误;

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

} 
+0

任何直接的帮助将更有帮助谢谢 – user2877014

+0

如果你可以用arraylist代替,那么你可以避免做任何不检查的转换 –

回答

0

Java不允许创建通用数组。您将必须投它

Q = new (E[]) Object[N]; 
2

错误是,在Java中,创建一个不可修饰类型的新实例是非法的。不可修饰类型是在编译时存在但在运行时不存在的类型。

Java中的泛型是通过擦除来实现的,也就是说所有的泛型类型参数在编译期间被编译器擦除。因此,泛型类型信息在运行时不存在。出于这个原因,不允许创建通用数组,因为编译器不能保证在运行时数组上的所有操作都是类型安全的。因此,编译器会产生错误。

以下非reifiable类型不能为数组被Java创建(E是一个泛型类型参数):

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

可以投一个数组转换为泛型类型,程序将编译...但是,如果出现错误,您将收到关于未经检查的转换的警告。同样,类型信息在运行时不存在,所以警告提醒您您的代码可能不是类型安全的。

您可以使用List<E>代替E[N]来绕过您的问题。由于Java数组是协变的(使数组在运行时可以知道它们的组件类型),而泛型集合是不变的(通用类型信息在运行时不存在;编译器强制执行类型安全性),所以数组和泛型混合很差。