2018. 6. 28. 19:10
# Question
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 = ???;
# Answer
Given:
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 anUnsupportedOperationException
. - 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.
source: https://stackoverflow.com/questions/157944/create-arraylist-from-array
'Language > java' 카테고리의 다른 글
우분투에서 자바(Java) 설치하는 방법 (쉬워요) (0) | 2018.12.22 |
---|---|
How do I generate random integers within a specific range in Java? (0) | 2018.06.28 |
Differences between HashMap and Hashtable? (0) | 2018.06.28 |
Read/convert an InputStream to a String (0) | 2018.06.28 |