Java 9中的Convenience Factory Method返回的特定集合类型 [英] Specific Collection type returned by Convenience Factory Method in Java 9
问题描述
在Java 9中,我们有方便工厂方法来创建和实例化不可变的List,Set和Map。
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.
例如:
List list = List.of("item1", "item2", "item3");
在这种情况下,实际返回了哪种类型的列表?它是一个ArrayList或LinkedList还是其他类型的List?
In this case which type of list is actually returned? Is it an ArrayList or a LinkedList or some other type of List?
API文档刚提到这一行,没有明确提到它的LinkedList:
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.
推荐答案
List.of
是包私有静态类之一,因此不属于公共API:
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 {
...
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
接口合约。
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.
这篇关于Java 9中的Convenience Factory Method返回的特定集合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!