将Iterables转换为Collection会迭代所有元素吗?

mer*_*ert 1 java guava

这是Iterables.isEmpty()(ref)的源代码:

public static boolean isEmpty(Iterable<?> iterable) {
    if (iterable instanceof Collection) {
      return ((Collection<?>) iterable).isEmpty();
    }
    return !iterable.iterator().hasNext();
}
Run Code Online (Sandbox Code Playgroud)

我想知道如果Iterables.isEmpty()给定iterable参数是一个Set扩展的类型,方法是否迭代所有元素Collection.难道铸造IterableCollection原因完整的迭代?如果是这样,为什么?如果没有,为什么不呢?

And*_*ner 7

我想知道Iterables.isEmpty()如果给定方法迭代所有元素iterable

否:Iterables.isEmpty() iterable.iterator().hasNext()针对非Collections 实施的.它永远不会比第一个元素更进一步.

Cast Iterable to Collection是否会导致完全迭代

不,Casting对该对象没有任何作用,它只是告诉编译器"信任你"它可以被视为子类,而不是超类.

来自JLS Sec 15.6:

转换表达式...在运行时检查引用值是指其类与指定引用类型或引用类型列表兼容的对象.