Java 9为列表引入了一种新的工厂方法List.of:
List<String> strings = List.of("first", "second");
Run Code Online (Sandbox Code Playgroud)
前一个和新选项有什么区别?也就是说,这有什么区别:
Arrays.asList(1, 2, 3);
Run Code Online (Sandbox Code Playgroud)
还有这个:
List.of(1, 2, 3);
Run Code Online (Sandbox Code Playgroud) 作为List.of(...)或Collections.unmodifiableList()的一个特例- 指向空的和不可变列表的首选Java 9方式是什么?
继续写
Collections.emptyList();
Run Code Online (Sandbox Code Playgroud)
或切换到
List.of();
Run Code Online (Sandbox Code Playgroud) 在List.of()或Collections.emptyList()和List.of(...)或Collections.unmodifiableList()中给出的注释和答案的上下文中, 我提出了两条以下经验法则(也适用于Set和Map工厂相应).
继续使用Collections.emptyList()以提高可读性,例如初始化懒惰的字段成员,例如:
class Bean {
private List<Bean> beans = Collection.emptyList();
public List<Bean> getBeans() {
if (beans == Collections.EMPTY_LIST) { beans = new ArrayList<>(); }
return beans;
}
}
Run Code Online (Sandbox Code Playgroud)
在使用参数List.of()调用可执行文件时,使用新工厂和变体作为快速且较少类型的版本List.以下是我目前的替代模式:
Collections.emptyList() --> List.of()
Collections.singletonList(a) --> List.of(a)
Arrays.asList(a, ..., z) --> List.of(a, ..., z)
Run Code Online (Sandbox Code Playgroud)
在虚构的用法中Collections.indexOfSubList,以下几行
Collections.indexOfSubList(Arrays.asList(1, 2, 3), Collections.emptyList());
Collections.indexOfSubList(Arrays.asList(1, 2, 3), Collections.singletonList(1));
Collections.indexOfSubList(Arrays.asList(1, 2, 3), Arrays.asList(1));
Collections.indexOfSubList(Arrays.asList(1, 2, 3), Arrays.asList(2, 3));
Collections.indexOfSubList(Arrays.asList(1, …Run Code Online (Sandbox Code Playgroud) Java 10的发布带来了新的静态工厂方法,特别是:
static <E> List<E> copyOf?(Collection<? extends E> coll)static <E> Set<E> copyOf?(Collection<? extends E> coll)static <K,V> Map<K,V> copyOf?(Map<? extends K,? extends V> map)看到这些方法允许我们将Collections 复制到不同的Collection实现中,它们如何与现有方法进行比较和对比?