相关疑难解决方法(0)

Java 9集合工厂的用法

List.of()或Collections.emptyList()List.of(...)或Collections.unmodifiableList()中给出的注释和答案的上下文中, 我提出了两条以下经验法则(也适用于SetMap工厂相应).

  1. 不要替换所有出现的事件

继续使用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)
  1. 使用新工厂作为方法参数构建器

在使用参数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 collections java-9

10
推荐指数
2
解决办法
581
查看次数

标签 统计

collections ×1

java ×1

java-9 ×1