Effective-Java-54返回零长度的数组或集合,而不是null

将null而不是0长度的数组或集合返回是不合常理的,这使得客户端中必须得有额外代码以处理null的代码。[1]编写客户端程序的程序员有可能忘记写代码来处理null,这样的错误可能很久都不会被发现。返回null也会使得其实现代码更加复杂。[2]

有时候会有人认为: null返回值会比零长度集合或数组更好,因为它避免了分配长度容器所需的开销。这种观点是站不住脚的,原因有二:[3]

  1. 在这个级别上担心性能问题是不明智的,除非分析表明这个方法正是造成性能问题的原因(见67条)。[4]
  2. 不需要分配零长度的集合或者数组,也可以返回他们。

如果切实造存在性2能问题,可以通过重复返回一个不可变的零长度集合(例如 Collections.emptyList() Collections.emptyMap() ),避免即时分配,因为不可变类可以被自由的共享(见17条)。[5]这仅是一个优化,几乎用不上。如果您认为确实有必要,请在行动前后进行性能测试。

简而言之,返回一个零长度的数组或集合,而不是null。如果返回null,那样会使得API更加难用,也更容易出错,且没有任何的性能优势。[6]


  1. Joshua Bloch, Effective Java, 3rd Edition, Item 54, gives the rule to return empty collections or arrays instead of null. ↩︎

  2. Effective Java Item 54 frames null collection returns as an API contract cost because every caller must remember and handle the extra path. ↩︎

  3. Effective Java Item 54 directly addresses the claim that returning null avoids allocating empty containers. ↩︎

  4. Effective Java Item 54 ties this performance concern to the broader measurement-first rule in Item 67: optimize only when profiling shows the method is actually a problem. ↩︎

  5. Oracle Java SE 21 API documents Collections.emptyList(), emptySet(), and emptyMap() as immutable empty collection factories; List.of() is also an unmodifiable list factory. ↩︎

  6. The same boundary is reflected in Oracle’s Optional documentation: Optional<T> represents the possible absence of one non-null value, while collection APIs already have a natural zero-element value. ↩︎