tags:

views:

548

answers:

3

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);
}
+6  A: 
ArrayList<ProductListBean> productList = (ArrayList<ProductListBean>)getProductsList();

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

Matthew Flaschen
+2  A: 

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.

Brian Agnew
A: 

The way you describe is typesafe (well not really, but it will throw a ClassCastException if you got it wrong), but probably the slowest and the most verbose way of doing this (although it is pretty clear). The example given which simply casts the the ArrayList is the fastest, but as the poster points out is not typesafe and of course you probably want to copy that to another list anyway. If you are prepared to give up your need to have this copied to an ArrayList and are happy with a List instead (which you should be), simply do:

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

It's fast because the underlying copying is done with System.arraycopy which is a native method, and it's typesafe (well again not really, but it's as safe as your example) because System.arraycopy will throw an ArrayStoreException if you try to add something that's not of the same type.

Dean Povey