所以我有一个产品数组列表,我在类别类的开头实例化......
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;
}
运行程序时,出现“Exception in thread "main"java.lang.ClassCastException: java.base/[Ljava.lang.O 对象;无法在 getAllProducts() 方法的 'for' 循环中转换为 [L...Product;"。
我很困惑为什么会收到此异常,因为 .toArray() 应该返回 Product[]。有没有更简单的方法来深度复制并返回这个ArrayList?
最佳答案
嗯,ArrayList
实现了 Cloneable
接口(interface)。因此,您可以做的一件好事就是开始阅读标准库的代码。我提取了这个具体方法:
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
*
* @return a clone of this <tt>ArrayList</tt> instance
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
我建议您始终尝试从中学习。我希望它能有所帮助。
关于java - 复制另一个 ArrayList 的 ArrayList 时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58720790/