在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)