It seems to be a silly question at the first sight, but I found that the mechanism isn't trivial. The implementation from JDK 8
(copied from here) is just a few lines:
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
The point is that there are only 3 constructors in ArrayList
:
int
(the initial capacity)Collection
(the elements) as shown below (copied from here):public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
// ...
transient Object[] elementData; // non-private to simplify nested class access
private int size;
// ...
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
// ...
}
Since the only possibility is that the 3rd constructor is called, it seems that the parameter a
(the generic vararg) is somehow "casted" to a Collection
. But as far as I know, varargs are nothing more than arrays with a shorter syntax, and are not convertible to Collection
s (so that's why this made me puzzled)...
Does anybody know how the magic works?
Thank you!
asList returns a fixed-size list that is backed by the specified array; the returned list is serializable and allows random access.
Understanding Arrays. Before we move ahead, the next snippet shows how to create a list from array using asList method. However, the asList method does not convert array, neither it copies elements.
Yes. A List, by definition, always preserves the order of the elements. This is true not only of ArrayList, but LinkedList, Vector, and any other class that implements the java.
util. Arrays. asList() , the list is immutable.
You're looking at the wrong ArrayList
class. The one used in Arrays.asList(..)
is java.util.Arrays.ArrayList
and has a constructor that accepts an array.
The ArrayList
type that's described here is not java.util.ArrayList
; it's a private type defined inside that file (see line 3799). That one does have an array constructor, and it's the one referenced by Arrays.asList
.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With