代码之家  ›  专栏  ›  技术社区  ›  ViaTech

对象无法转换为E-自定义ArrayList[重复]

  •  -2
  • ViaTech  · 技术社区  · 7 年前

    我遇到了泛型转换错误。如果需要,我可以提供完整的代码,但我觉得我缺少了一些非常简单的东西。我试图在我的类中使用一个方法将输入列表的所有元素添加到当前列表中,但我得到了E的转换错误。

    有人能给我指出我需要做什么的正确方向吗?-我对编程并不陌生,但Java不是我的第一语言。

    public class ArrayList<E> implements List<E> {
    // instance variables
    /** Default array capacity. */
    public static final int CAPACITY=16;     // default array capacity
    
    private E[] data;                        // generic array used for storage
    
    
    private int size = 0;                    // current number of elements
    
    public ArrayList() { this(CAPACITY); }   // constructs list with default capacity
    
    
    @SuppressWarnings({"unchecked"})
    public ArrayList(int capacity) {         // constructs list with given capacity
    data = (E[]) new Object[capacity];     // safe cast; compiler may give warning
    }
    
    // public methods
    public int size() { return size; }
    
    
    public boolean isEmpty() { return size == 0; }
    
    
    public E get(int i) throws IndexOutOfBoundsException {
    checkIndex(i, size);
    return data[i];
    }
    
    public void add(int i, E e) throws IndexOutOfBoundsException {
    checkIndex(i, size + 1);
    if (size == data.length)               // not enough capacity
      resize(2 * data.length);             // so double the current capacity
    for (int k=size-1; k >= i; k--)        // start by shifting rightmost
      data[k+1] = data[k];
    data[i] = e;                           // ready to place the new element
    //print(data[i].getClass());//STRING BASED ON CURRENT TEST CODE
    size++;
    }
    
    //-------ERROR CODE
    public void addAll(ArrayList l){
        //Adds all elements in l to the end of this list, in the order that they are in l.
        //Input: An ArrayList l.
        //Output: None
        //Postcondition: All elements in the list l have been added to this list.
    
        //add(int i, E e)
        //l IS ALSO AN ARRAY LIST SO SAME METHODS/VARIABLES APPLY...JUST REFERENCE l'S VERSION
    
        //add(0,"hi");//ERROR NOT E
    
        int foundSize = l.size();
        //print(foundSize);
        print("SIZE:"+size);
        print("LENGTH:"+data.length);//TOTAL
    
        for (int i=0; i < foundSize; i++){
            //print(data[i]);
            this.add(size(), l.get(i));//INCOMPATIBLE TYPES 
    
        }
    
    
    }
    
    //-------ERROR CODE
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Eran    7 年前

    你正在通过一个未经处理的 ArrayList 到您的 addAll 方法

    改变

    public void addAll(ArrayList l)
    

    public void addAll(ArrayList<E> l)
    
    推荐文章