【问题标题】:Where exactly the java.util.Collections.emptyList() method is used in real application? [duplicate]java.util.Collections.emptyList() 方法在实际应用程序中到底在哪里使用? [复制]
【发布时间】:2020-08-04 12:45:45
【问题描述】:

我只是想知道 java.util.Collections.emptyList() 方法的具体用途。为什么给出这样的方法,它在 Java 中返回不可变列表?可以用它做什么?

【问题讨论】:

标签: java collections empty-list


【解决方案1】:

当你想返回一个空列表时它很有用。重用一个规范的空列表比每次都创建一个新列表更有效。

List<Integer> numbersBetween(int from, int to) {
  if (to < from) return Collections.emptyList();
  else {
    //do what you have to do
  }
}

【讨论】:

    【解决方案2】:

    在遗留应用程序中,使用 null 值而不是空列表、集合或映射是很常见的。

    public List<String> getElements() {
      if (bla < 0) {
        return null;
      }
    }
    
    public List<String> getElements() {
      if (bla < 0) {
        return Collections.emptyList();
      }
    }
    
    

    在我看来,最好使用空的 List&lt;&gt;Set&lt;&gt;Map&lt;&gt; 而不是 null 值。

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 2012-02-18
      • 2011-09-02
      • 2018-11-07
      相关资源
      最近更新 更多