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

Does casting Iterables to Collection iterates over all the elements?

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

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

我想知道如果给定的 iterable 参数是 Set 的一种类型,它扩展了 CollectionIterables.isEmpty() 方法是否会遍历所有元素。将 Iterable 转换为 Collection 会导致完整迭代吗?如果是这样,为什么?如果不是,为什么不呢?

I am wondering if Iterables.isEmpty() method iterates over all the elements if given iterable

否:Iterables.isEmpty()is implemented as iterable.iterator().hasNext() for non-Collections。它永远不会超过第一个元素。

Does casting Iterable to Collection causes full iteration

没有。转换对对象没有任何作用,它只是告诉编译器 "trust you" 它可以被视为子类,而不是超类。

来自JLS Sec 15.6

A cast expression ... checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type or list of reference types.