Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an untyped Arraylist to a typed Arraylist

Tags:

java

arraylist

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);
}
like image 938
Amoeba Avatar asked Dec 07 '22 07:12

Amoeba


2 Answers

ArrayList<ProductListBean> productList = (ArrayList<ProductListBean>)getProductsList();

Note that this is inherently unsafe, so it should only be used if getProductsList can't be updated.

like image 137
Matthew Flaschen Avatar answered Feb 14 '23 01:02

Matthew Flaschen


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.

like image 31
Brian Agnew Avatar answered Feb 14 '23 01:02

Brian Agnew