复制另一个ArrayList的ArrayList时引发异常

所以我有一个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?

christianshengbing 回答:复制另一个ArrayList的ArrayList时引发异常

好吧,ArrayList实现了Cloneable接口。因此,您可以做的一件好事是开始阅读标准库的代码。我提取了这种特定方法:

    /**
     * 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);
        }
    }

我建议您始终尝试从中学到东西。希望对您有所帮助。

本文链接:https://www.f2er.com/3155893.html

大家都在问