java - 复制另一个 ArrayList 的 ArrayList 时抛出异常

标签 java arraylist casting

所以我有一个产品数组列表,我在类别类的开头实例化......

    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/

相关文章:

java - 为什么单例 ArrayList 在间接更改其中一项时会受到影响?

ios - 应避免强制转换

java - 无法转换为子类

java - MaterialAnimatedSwitch 保存状态

c++ - 在类中创建动态数组 (C++)

java - 将位图压缩到Android中的特定字节大小

java - 添加 ArrayList 后清除某些内容也会清除 ArrayList

c++ - 如何通过转换类型指针将 char 数组转换为 uint16_t?

java机器人转弯不足转向

java - Ruby 对象到 Java 对象