Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 932
user192472 Avatar asked Jan 21 '23 15:01

user192472


2 Answers

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);    
}
like image 186
skaffman Avatar answered Jan 28 '23 19:01

skaffman


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.

like image 30
jvdneste Avatar answered Jan 28 '23 17:01

jvdneste