Convert list to array python stack overflow
How to Convert Array to ArrayList in Java?Category: Collections April 16, 2013 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)}; 1. Most popular and accepted answer The most popular and the accepted answer is the following:
ArrayList First, let's take a look at the Java Doc for the constructor method of ArrayList.
So what the constructor does is the following: Here is the source code of Contructor of ArrayList.
public ArrayList(Collection c) { elementData = c.toArray(); size = elementData.length; if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } 2. Next popular answer The next popular answer is:
List It is not the best, because the size of the list returned from asList() is fixed. Actually the list returned is not java.util.ArrayList, but a private static class defined inside java.util.Arrays. We know ArrayList is essentially implemented as an array, and the list returned from asList() is a fixed-size list backed by the original array. In this way, if add or remove elements from the returned list, an UnsupportedOperationException will be thrown.
list.add(new Element(4)); 3. Another Solution This solution is from Otto's comment below.
Element[] array = {new Element(1), new Element(2)}; List 4. Indications of the question The problem is not hard, but interesting. Every Java programmer knows ArrayList, but it's easy to make such a mistake. I guess that is why this question is so popular. If a similar question asked about a Java library in a specific domain, it would be less likely to become so popular. There are several answers that provide the same solution. This is also true for a lot of other questions on Stack Overflow, I guess people just don't care what others say if they would like to answer a question! Reference: The stackoverflow question link Related posts:
|