Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning cloning ArrayList in Java

public void addProductList(ArrayList<ViewOrderProduct> globalOrderProductList) {

    this.productOrderList =  (ArrayList<ViewOrderProduct>)globalOrderProductList.clone();
}

This gives me the warning:

Type safety: Unchecked cast from Object to ArrayList

I know that I can simply solve the problem adding @SuppressWarnings("unchecked").

But I want understand the problem. I can be sure that all goes good if I add the suppressWarnings? Is there another solution for this warning?

like image 696
GVillani82 Avatar asked Aug 17 '26 08:08

GVillani82


1 Answers

clone() returns Object by default, the correct way to clone an ArrayList is to use the appropriate constructor:

this.productOrderList =  new ArrayList<ViewOrderProduct>(globalOrderProductList);

Edit: The preferred way is to use the appropriate constructor, and both methods only return a shallow copy anyways.

Edit: And there's no other way I'm aware of, to remove the warning using clone() without a SuppressWarning.

like image 63
Neet Avatar answered Aug 19 '26 09:08

Neet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!