Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific Collection type returned by Convenience Factory Method in Java 9

In Java 9 we have convenience factory methods to create and instantiate immutable List, Set and Map.

However, it is unclear about the specific type of the returned object.

For ex:

List list = List.of("item1", "item2", "item3");

In this case which type of list is actually returned? Is it an ArrayList or a LinkedList or some other type of List?

The API documentation just mentions this line, without explicitly mentioning that its a LinkedList:

The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.

like image 784
Curious Coder Avatar asked Nov 28 '22 13:11

Curious Coder


1 Answers

The class returned by List.of is one of the package-private static classes and therefore not part of the public API:

package java.util;
...

class ImmutableCollections {
    ...

    // Java 9-10
    static final class List0<E> extends AbstractImmutableList<E> {
        ...
    }

    static final class List1<E> extends AbstractImmutableList<E> {
        ...
    }

    static final class List2<E> extends AbstractImmutableList<E> {
        ...
    }

    static final class ListN<E> extends AbstractImmutableList<E> {
        ...
    }


    // Java 11+
    static final class List12<E> extends AbstractImmutableList<E> {
        ...
    }

    static final class ListN<E> extends AbstractImmutableList<E> {
        ...
    }
}

So this is not an ArrayList (neither a LinkedList). The only things you need to know is that it is immutable and satisfies the List interface contract.

like image 135
ZhekaKozlov Avatar answered Dec 17 '22 04:12

ZhekaKozlov