所以我有一个ArrayList of Products,我在Category类的开头实例化了这个例子。
private ListInterface<Product> products;
public Category(String categoryName) {
products = new ArrayList<Product>();
}
我想使用以下方法返回特定类别的所有产品的深层副本...
public ListInterface<Product> getallProducts() {
ListInterface<Product> temp = new ArrayList<Product>();
for (Product prod : products.toArray()) // CAST EXCEPTION HERE
temp.add(prod);
return temp;
}
这是toArray()方法...
public E[] toArray() {
@SuppressWarnings("unchecked")
E[] result = (E[])new Object[size];
for (int index = 0; index < size; index++) {
result[index] = list[index];
}
return result;
}
运行程序时,我在线程“ main”中得到“ Exception” java.lang.ClassCastException:java.base / [Ljava.lang.O 撞不能在getallProducts()方法的'for'循环中转换为[L ... Product;“。
由于为什么要获取此异常,我感到困惑,因为.toArray()应该返回Product []。有没有更简单的方法来深度复制并返回此ArrayList?