HOW TO CONVERT ARRAYLIST (ARRAYLIST<T>) FROM ARRAY (T[])

Royce Roy

Total Post:149

Points:1043
Posted by  Royce Roy
Java 
 857  View(s)
Ratings:
Rate this:

I have an array that is initialized like:

Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this array into an object of the ArrayList class.

ArrayList<Element> arraylist = ???;
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How to convert ArrayList (ArrayList<T>) from array (T[])

    Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };
    The simplest answer is to do:

    List<Element> list = Arrays.asList(array);
    This will work fine. But some caveats:

    The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you'll need to wrap it in a new ArrayList. Otherwise you'll get an UnsupportedOperationException.
    The list returned from asList() is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!