2015-06-19 24 views
4

我一直在嘗試訪問數組列表中保存的幾個數組的元素。我可以定期訪問它,但是當我使用泛型類型E來說明不同的數據類型時,問題就出現了。這給了我一個類演員異常。如果我將tempStart和tempScan的類型以及相應的強制類型轉換爲int [](因爲這是我用來傳入的),它會運行。如何訪問陣列的通用數組列表中的元素

public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) { 
    if (list.get(0).getClass().isArray()) { 
     System.out.println(" I am an array!"); 
     //go through the arrays and make sure they are 
     //not the same, remove any that are the same 
     //make flag to see if something is different 
     boolean matching; 
     for (int idx = 0; idx < list.size() - 1; idx++) { 
      E[] tempStart =(E[])list.get(idx); 
      for (int k = idx + 1; k < list.size(); k++) { 
       matching = true; 
       E[] tempScan = (E[])list.get(k); 
       for (int index = 0; index < tempStart.length; index++) { 
        if (tempStart[index] != tempScan[index]) { 
         matching = false; 
        } 
       } 
       if (matching) { 
        list.remove(tempScan); 
        k--; 
       } 
      } 
     } 
+0

您的for循環遍歷list.size。你是否正在檢查數組中的兩個數組是否相同,或者數組中的元素是否相同? – lmcphers

回答

4

您試圖投EE[]和這顯然不正確。因爲我們使用Java反射陣列操縱數組操作,使用通用E無厘頭這裏

import java.lang.reflect.Array 
... 
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) { 
    ArrayList<E> retList = new ArrayList<>(list.size()); 
    if (list.isEmpty()) return retList; 
    if (list.get(0).getClass().isArray()) { 
     boolean matching; 
     for (int idx = 0; idx < list.size() - 1; ++idx) { 
      E tempStart = list.get(idx); 
      for (int k = idx + 1; k < list.size(); k++) { 
       matching = true; 
       E tempScan = list.get(k); 
       int tempStartLen = Array.getLength(tempStart); 
       for (int index = 0; index < tempStartLen; index++) { 
        if (Array.get(tempScan, index) != Array.get(tempStart, index)) { 
         matching = false; 
        } 
       } 
       if (matching) { 
        list.remove(tempScan); 
        k--; 
       } 
      } 
     } 
     return retList; 
    } else { 
     throw new IllegalArgumentException("List element type expected to be an array"); 
    } 
} 

但是:你可以試試。你可以簡單的聲明爲ArrayList<Object>

更新:如下@afsantos評論,參數類型ArrayList可以作爲沒有什麼會被插入到它被聲明爲ArrayList<?>

+0

該方法的'list'參數可以使用通配符,因爲沒有元素被插入:'ArrayList list'。 – afsantos

+0

工作!我正在從事一項需要我們使用泛型類型的學校任務,所以這就是我處於這種奇怪狀況的原因。謝謝! – cashew

+1

請記住,解決方案不是使用泛型類型的一種方式。實際上使用泛型與數組不是一個好主意。請參閱http://stackoverflow.com/questions/1817524/generic-arrays-in-java –