Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does java.util.Arrays.asList(T...) work?

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:

  • one doesn't take any parameter
  • one takes an int (the initial capacity)
  • one takes a 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 Collections (so that's why this made me puzzled)...

Does anybody know how the magic works?

Thank you!

like image 389
Siu Ching Pong -Asuka Kenji- Avatar asked Aug 04 '14 05:08

Siu Ching Pong -Asuka Kenji-


People also ask

What does array asList return?

asList returns a fixed-size list that is​ backed by the specified array; the returned list is serializable and allows random access.

Does array copy asList?

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.

Does Arrays asList maintain order?

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.

Are Arrays asList Unmodifiable?

util. Arrays. asList() , the list is immutable.


2 Answers

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.

like image 127
Sotirios Delimanolis Avatar answered Sep 28 '22 07:09

Sotirios Delimanolis


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!

like image 44
templatetypedef Avatar answered Sep 28 '22 09:09

templatetypedef