The specific collection type returned by the Factory convenience method in Java 9

In Java 9, we have convenient factory methods for creating and creating immutable lists, sets, and maps.

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

For ex:

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

In this case, what type of list is really returned? Is this an ArrayList or LinkedList or some other type of List?

The API documentation just mentions this line without explicitly specifying that its LinkedList:

The order of the items in the list matches the order of the arguments or items in the provided array.

+4
source share
5 answers

, List.of, , , API:

package java.util;
...

class ImmutableCollections {
    ...

    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> {
        ...
    }
}

, ArrayList ( LinkedList). , , , List.

+7

, .

, ! , List<Whatever> . , , , List. , , , .

, , ! , , !

: - , raw , ( List ).

+8

, -, @ZhekaKozlov @GhostCat (ImmutableCollections.List), , API. , factory , List.


ImmutableCollections, , . List, Map Set.


ImmutableCollections factory List, :

abstract static class AbstractImmutableList<E>

AbstractList UnsupportedOperationException , . , , Java .

,

static final class ListN<E> extends AbstractImmutableList<E>

NonNull, , E[] elements ( E), .get(int idx), .contains(Object o) .


, Map Set, , . , ( IllegalArgumentException NullPointer ):

Set<String> set2 = Set.of("a", "b", "a");
Map<String,String> map = Map.of("key1","value1","key1","value1");

Set<String> set2 = Set.of("a", null);
Map<String,String> map = Map.of("key1",null);
+4

Collectors.toList, : List , : There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned. ArrayList, , , .

I wonder if you need to do the same here - explicitly indicate that type Listand nothing more. This provided a ton of opportunities for future implementations to decide which type would return that would fit best - speed, space, etc.

+4
source

List.ofreturns a Listspecial type of type Collections.UnmodifiableList. This is not ArrayListand LinkedList. It will throw an exception when you try to change it.

+3
source

Source: https://habr.com/ru/post/1684095/


All Articles