开发者

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

开发者 https://www.devze.com 2023-01-10 23:06 出处:网络
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_somethi

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. Per开发者_如何转开发haps 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.)


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);    
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消