Is there a more elegant solution to convert an 'Arraylist
' into a 'Arraylist<Type>
'?
Current code:
ArrayList productsArrayList=getProductsList();
ArrayList<ProductListBean> productList = new ArrayList<ProductListBean>();
for (Object item : productsArrayList)
{
ProductListBean product = (ProductListBean)item;
productList.add(product);
}
ArrayList<ProductListBean> productList = (ArrayList<ProductListBean>)getProductsList();
Note that this is inherently unsafe, so it should only be used if getProductsList can't be updated.
Look up type erasure with respect to Java.
Typing a collection as containing ProductListBean
is a compile-time annotation on the collection, and the compiler can use this to determine if you're doing the right thing (i.e. adding a Fruit
class would not be valid).
However once compiled the collection is simply an ArrayList
since the type info has been erased. Hence, ArrayList<ProductListBean>
and ArrayList
are the same thing, and casting (as in Matthew's answers) will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With