mert
mert

Reputation: 2002

Does casting Iterables to Collection iterates over all the elements?

Here is the source code for Iterables.isEmpty() (ref):

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

I am wondering if Iterables.isEmpty() method iterates over all the elements if given iterable parameter is a type of Set, which extends Collection. Does casting Iterable to Collection causes full iteration? If so, why? If not, why not?

Upvotes: 1

Views: 124

Answers (1)

Andy Turner
Andy Turner

Reputation: 140534

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

No: Iterables.isEmpty() is implemented as iterable.iterator().hasNext() for non-Collections. It never goes further than that first element.

Does casting Iterable to Collection causes full iteration

No. Casting does nothing to the object, it just tells the compiler to "trust you" that it can be treated as the subclass, rather than the superclass.

From 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.

Upvotes: 7

Related Questions