gpt4 book ai didi

java - Java 9 中便利工厂方法返回的特定集合类型

转载 作者:搜寻专家 更新时间:2023-11-01 01:00:05 25 4
gpt4 key购买 nike

在 Java 9 中,我们有方便的工厂方法来创建和实例化不可变的 List、Set 和 Map。

但是具体返回对象的类型还不清楚。

例如:

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

在这种情况下,实际返回的是哪种类型的列表?它是 ArrayList 还是 LinkedList 或其他类型的列表?

API 文档只提到这一行,没有明确提到它是一个 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.

最佳答案

List.of 返回的类是包私有(private)静态类之一,因此不是公共(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> {
...
}
}

所以这不是 ArrayList(也不是 LinkedList)。您唯一需要知道的是它是不可变的 并且满足List 接口(interface)契约。

关于java - Java 9 中便利工厂方法返回的特定集合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45791676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com