How to Convert Array to ArrayList in Java?
This article analyzes answers for a top-voted questions on Stack Overflow. The person who asked this question got a lot of reputation points, which could grant him permissions to do a lot of things on Stack Overflow. This does not make sense to me, but let's take a look at the question first.
The question is "how to convert the following array to an ArrayList?".
Element[] array = {new Element[1],new Element[2],new Element[3]}; |
Element[] array = {new Element[1],new Element[2],new Element[3]};
1. Most popular and accepted answer
The most popular and the accepted answer is the following:
ArrayList arrayList = new ArrayList[Arrays.asList[array]]; |
ArrayList arrayList = new ArrayList[Arrays.asList[array]];
First, let's take a look at the Java Doc for the constructor method of ArrayList.
ArrayList[Collection < ? extends E > c] : Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
So what the constructor does is the following:
1. Convert the collection c to an array
2. Copy the array to ArrayList's own back array called "elementData"
Here is the source code of Contructor of ArrayList.
public ArrayList[Collection
Chủ Đề |