我遇到了Generics的转换错误。如果需要,我可以提供完整的代码,但我觉得我错过了一些非常简单的东西。我试图在我的类中使用一个方法将输入列表的所有元素添加到当前列表,但我收到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
答案 0 :(得分:0)
您正在将原始ArrayList
传递给addAll
方法。
更改
public void addAll(ArrayList l)
到
public void addAll(ArrayList<E> l)