2011-06-30 49 views
0

從參數數組我已經實現數組列表與數組:Java創建

public class ArrayIndexList<E> { 
    private E[] A; 
    private int capacity = 5; // Initial Array Size 
    private int size = 0; 

    public ArrayIndexList() { 
     A = (E[]) new Object[capacity]; 
    } 

    public void add(int index, E element) { 
     /* if array is full: 
     * 1. double the array size 
     * 2. copy elements to the new array */ 
     if (size == capacity) { 
      capacity = capacity * 2; 
      E[] B = (E[]) new Object[capacity]; 
      for (int i = 0;i < size;i++) 
      B[i] = A[i]; 
      A = B; 
     } 

     // shift the elements up 
     for (int i = size - 1;i >= index;i--) 
      A[i + 1] = A[i]; 

     // add new element 
     A[index] = element; 
     size = size + 1; 
    } 

    public E remove(int index) { 
     E temp = A[index]; 

     //shift elements down 
     for (int i = index;i < size - 1;i++) 
      A[i] = A[i + 1]; 
     size = size - 1; 

     return temp; 
    } 
} 

這是工作,但編譯器會發出警告:

Type safety: Unchecked cast from Object[] to E[] ArrayIndexList.java 

有什麼不好的代碼?

回答

1

你實際上是一種撒謊當你從Object[]轉換爲E[],因爲數組在運行時保持它們的組件類型,所以它不是在現實中可以從Object[]轉換爲更具體的數組類型;但由於您處於類型參數E的範圍內,因此E[]已被刪除,因此不會導致錯誤。

這實際上是你可以做的最好的,因爲唯一的其他選擇是使用變量「A」是Object[]型的,但你必須投進去E每次你得到的東西出來的時候,這會產生更多未經檢查的施放警告。你無法擺脫它,所以你只能壓制它們。 (除非你包裝一個預製的類型,做你的班級所做的那樣,ArrayList,它本身也是一樣的,並且必須在內部禁止這些警告)