user192472
user192472

Reputation: 745

Is there a most general "iterable" type accepted by Java for-each loops?

Is there a type XXX<T> that can be iterated on with for-each and subsumes both T[] and Iterable<T> so that the following compiles (assuming class context and a compatible method do_something) ?

public void iterate(XXX<T> items)
{
    for (T t : items)
        do_something(t);
}

public void iterate_array(T[] items)
{
    iterate(items);
}

public void iterate_iterable(Iterable<T> items)
{
    iterate(items);
}

In Java 1.5 I found nothing of the kind. Perhaps in a later version of the language ? (I guess it's probably a FAQ. Sorry for the noise if it is. A quick google search did not give the answer.)

Upvotes: 4

Views: 183

Answers (2)

skaffman
skaffman

Reputation: 403591

The short answer is: no, there is no type that covers both.

The simple solution is to wrap your array in a List, and then just invoke with that

public void iterate_array(T[] items)
{
    iterate(Arrays.asList(items));
}

public void iterate_array(Iterable<T> items)
{
    for (T t : items)
        do_something(t);    
}

Upvotes: 6

jvdneste
jvdneste

Reputation: 1677

This is related to many other questions regarding arrays and generics. There is no supertype for arrays and iterables (other than object). And this is a problem because generics and arrays are not very compatible. Unless you need primitive arrays for performance reasons (doubt it), stick to generic collections.

Upvotes: 3

Related Questions