为什么 FluentIterable.first() 在第一个元素为 null 时抛出 NPE

Why does FluentIterable.first() throw NPE when the first element is null

这是FluentIterable.first()的方法说明。

当第一个元素为 null 时,它抛出 NPE 而不是 return Optional.absent()

我认为它使 FluentIterable 具有影响力,并且 Optional 因为 return 值给我的印象是它是完全安全的。

我想知道为什么?谢谢。

正如您从下面的方法代码中看到的那样,FluentIterable.first 并未实现为处理具有空值的序列。返回类型中的Optional是为了处理序列为空的可能性。

方法代码如下:

  public final Optional<E> first() {
    Iterator<E> iterator = iterable.iterator();
    return iterator.hasNext()
        ? Optional.of(iterator.next())
        : Optional.<E>absent();
  }

请注意,如果提供的对象为空,Optional.of 将抛出 NPE。

P.S。对于第一个元素为 null 的情况返回 Optional.absent() 会使结果与空序列情况无法区分,这可能是一个问题。

这是一个 documented behavior:

public final Optional<E> first()

Returns an Optional containing the first element in this fluent iterable. If the iterable is empty, Optional.absent() is returned.

Throws:
NullPointerException - if the first element is null; if this is a possibility, use iterator().next() or Iterables.getFirst(java.lang.Iterable<? extends T>, T) instead.

重点是我的,作为解决方法请遵循上述建议。一般来说,Guava's collections are null-hostile.

在这种特殊情况下,抛出 NPE 以避免歧义,因为 Optional.absent()iterable 为空 时返回,而不是在第一个元素为 null 时返回.