2015-06-19 22 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 –