Create ArrayList from array

后端 未结 30 1821
遇见更好的自我
遇见更好的自我 2020-11-21 22:29

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

30条回答
  •  执笔经年
    2020-11-21 23:08

    Given:

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

    The simplest answer is to do:

    List list = Arrays.asList(array);
    

    This will work fine. But some caveats:

    1. 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.
    2. 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.

提交回复
热议问题