【问题标题】:Object Cannot Be Converted to E - Custom ArrayList [duplicate]对象无法转换为 E - 自定义 ArrayList [重复]
【发布时间】:2018-03-26 16:05:55
【问题描述】:

我遇到了泛型转换错误。如果需要,我可以提供完整的代码,但我觉得我错过了一些非常简单的东西。我试图在我的类中使用一种方法将输入列表的所有元素添加到当前列表中,但是我遇到了 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

【问题讨论】:

    标签: java generics type-conversion


    【解决方案1】:

    您正在将原始 ArrayList 传递给您的 addAll 方法。

    改变

    public void addAll(ArrayList l)
    

    public void addAll(ArrayList<E> l)
    

    【讨论】:

    • 快速提问,如果我想保留我的签名:public void addAll(ArrayList l),这可能吗?
    • @ViaTech 如果您这样做,您将能够将包含任何类型元素的ArrayList 传递给该方法。因此,您将无法将它们添加到您的 ArrayList&lt;E&gt; 中(除非您将它们中的每一个都转换为 E,这可能会在运行时抛出 ClassCastException)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2016-06-17
    • 2016-07-13
    • 2020-10-31
    • 2015-07-10
    • 1970-01-01
    • 2012-12-06
    相关资源
    最近更新 更多