java学习日志generic type(七)

先看自定义泛型一例:

Queue.java

public class Queue<E>
{
   private E[] elements;
   private int head, tail;
 
   @SuppressWarnings("unchecked")
   Queue(int size)
   {
      if (size < 2)
         throw new IllegalArgumentException("" + size);
       elements = (E[]) new Object[size];
       head = 0;
       tail = 0;
   }
 
   void insert(E element) throws QueueFullException
   {
      if (isFull())
         throw new QueueFullException();
      elements[tail] = element;
      tail = (tail + 1) % elements.length;
   }
 
   E remove() throws QueueEmptyException
   {
      if (isEmpty())
         throw new QueueEmptyException();

         E element = elements[head];
         head = (head + 1) % elements.length;
         return element;
   }
 
   boolean isEmpty()
   {
      return head == tail;
   }
 
   boolean isFull()
   {
      return (tail + 1) % elements.length == head;
   }
 
   public static void main(String[] args)
      throws QueueFullException, QueueEmptyException
   {
      Queue<String> queue = new Queue<String>(6);
      System.out.println("Empty: " + queue.isEmpty());
      System.out.println("Full: " + queue.isFull());
      System.out.println("Adding A");
      queue.insert("A");
      System.out.println("Adding B");
      queue.insert("B");
      System.out.println("Adding C");
      queue.insert("C");
      System.out.println("Adding D");
      queue.insert("D");
      System.out.println("Adding E");
      queue.insert("E");
      System.out.println("Empty: " + queue.isEmpty());
      System.out.println("Full: " + queue.isFull());
      System.out.println("Removing " + queue.remove());
      System.out.println("Empty: " + queue.isEmpty());
      System.out.println("Full: " + queue.isFull());
      System.out.println("Adding F");
      queue.insert("F");
      while (!queue.isEmpty())
         System.out.println("Removing " + queue.remove());
      System.out.println("Empty: " + queue.isEmpty());
      System.out.println("Full: " + queue.isFull());
	}
}

我们注意到 elements = (E[]) new Object[size];为什么这样声明呢?而不是 elements = new E[size];

这是因为java泛型的实现原则:数组创建的表达式中不能含有类型参数,也就是E[] elements = new E[size];是不对的;所以这样 new List<E>[50]也是错误的(a generic array creation error message)。

如果是在c++中,int *lpInt = new int[10];这是可以的。

而如果这样elements = (E[])new Queue<String>[size];也是不可以的,既然(定义一个泛型E)泛型声明,new的时候是不可以指定为实际的类型参数    String


虽然这样 elements = (E[]) new Queue<?>[size];是正确的表达,可以编译通过,但是运行的时候还是会报错:java.lang.ArrayStoreException;


java学习日志generic type(七)_第1张图片

这是因为企图填充一个无效的元素到数组中

你可能感兴趣的:(java)