For me, this is a matter of concern because it is stackoverflow and recommended. The people who raised such questions were widely praised, which enabled him to do many things on StackOverflow. Although it doesn't mean much to me, let's take a look at the problem first.
The question is as follows: How to convert the arrays array below to a ArrayList.
Element[] Array = {new Element (1), new Element (2), new Element (3)};
1. The most popular and accepted answers to the highest degree
The most popular and accepted answers are as follows:
arraylist<element> ArrayList = new Arraylist<element> (arrays.aslist (array));
First, let's take a look at how ArrayList is structured in Java documents:
ArrayList
-arraylist (Collection c)
creates a list containing all the elements in the specified collection, where the order of the elements is determined by the iterator of the specified collection
So, the constructor completes the work as follows:
1. Convert set C to an array of arrays
2. Copy array to ArrayList inside the array named "Elementdata"
If you call the Add () method now, the length of the elementdata array causes it to no longer add a new element. Therefore, you want to copy the array to a larger array. As the following code shows, the new array is 1.5 times times the length of the original array.
public void ensurecapacity (int mincapacity) {
modcount++;
int oldcapacity = elementdata.length;
if (Mincapacity > Oldcapacity) {
Object olddata[] = elementdata;
int newcapacity = (oldcapacity * 3)/2 + 1;
if (Newcapacity < mincapacity) {
newcapacity = mincapacity;
Mincapacity is usually very close to the actual size
}
elementdata = arrays.copyof (Elementdata, newcapacity);
}
2. The second most popular answer
The second most popular answer is:
list<element> list = arrays.aslist (array);
Because the size of the list returned by the Aslist () method is fixed, the method is not the best. As we know, ArrayList must be implemented by an array, and the Aslist () method returns a fixed-length list that relies on the original array, so that when you add or remove elements to the returned list, Throws a Unsupportedoperationexception exception.
List.add (New Element (4));
Exception in thread "main" Java.lang.classcastexception:java.util.arrays$arraylist cannot is cast to Java.util.ArrayList at collection. Convertarray.main (convertarray.java:22)
3. The implications of the issue
This question is not difficult, but also a bit interesting. Every Java programmer knows ArrayList, although it is simple to use, but also easy to make these mistakes. I guess that's why the problem is popular. Other similar problems with a range of Java class libraries are hard to be so popular.
There are many different answers to the same question. This is true for many problems, I guess people don't care about it, they just like to answer questions.
Source address: How to Convert Array to ArrayList in Java