So I have an ArrayList of Products that I instantiate at the beginning of my Category class...
private ListInterface<Product> products;
public Category(String categoryName) {
products = new ArrayList<Product>();
}
and I want to return a deep copy of all products of a specific category using the following method...
public ListInterface<Product> getAllProducts() {
ListInterface<Product> temp = new ArrayList<Product>();
for (Product prod : products.toArray()) // CAST EXCEPTION HERE
temp.add(prod);
return temp;
}
and here is the toArray() method...
public E[] toArray() {
@SuppressWarnings("unchecked")
E[] result = (E[])new Object[size];
for (int index = 0; index < size; index++) {
result[index] = list[index];
}
return result;
}
When running the program, I get "Exception in thread "main" java.lang.ClassCastException: java.base/[Ljava.lang.O bject; cannot be cast to [L...Product;" in the 'for' loop of the getAllProducts() method.
I am confused as to why I am getting this exception as .toArray() should return a Product[]. Is there an easier way to deep copy and return this ArrayList?