Convert untyped Arraylist to typed Arraylist

Is there a more elegant solution for converting ' Arraylist ' to ' Arraylist<Type> '?

Current code:

 ArrayList productsArrayList=getProductsList(); ArrayList<ProductListBean> productList = new ArrayList<ProductListBean>(); for (Object item : productsArrayList) { ProductListBean product = (ProductListBean)item; productList.add(product); } 
+4
source share
3 answers
 ArrayList<ProductListBean> productList = (ArrayList<ProductListBean>)getProductsList(); 

Please note that this is inherently unsafe, therefore it should be used only if getProductsList cannot be updated.

+10
source

Finding the erase type in relation to Java.

Entering a collection containing ProductListBean is an annotation of the compilation time in the collection, and the compiler can use this to determine if you are doing the right thing (for example, adding the Fruit class is not valid).

However, after compilation, the collection is simply an ArrayList , since the type information has been deleted. Therefore, ArrayList<ProductListBean> and ArrayList are one and the same, and casting (as in Matthew's answers) will work.

+4
source

The way you describe is typafe (actually it is not, but it will throw a ClassCastException if you're wrong), but probably the slowest and surest way to do this (although this is pretty clear). The above example, which simply distinguishes ArrayList, is the fastest, but, as the poster indicates, is not typical, and, of course, you probably want to copy it to another list. If you are ready to give up the need to copy it into an ArrayList and are happy with the list instead (which should be yours), simply do:

 List<ProductListBean> productList = Arrays.asList(((List<ProductListBean>)getProductsList()).toArray(new ProductListBean[] {})); 

This is fast because basic copying is done using System.arraycopy, which is a native method, and it types types (well, not exactly, but it is safe, as your example), because System.arraycopy will throw an ArrayStoreException if you try to add something that is not of the same type.

+1
source

All Articles