开发者

Java arrays and foreach iteration implementation

Is there some interface that will allow for iteraction of arrays and java.util.Lists?

Seeing as how the for-each loop can iterate both it seems to me there must be some sort of base 'iterable' that is being traversed in both cases.

So, can i setup a method parameter that accepts either Foo[], or List?

W开发者_运维问答e have lots of old code (which we won't be updating), that calls a few low level methods (which i'd like to update) that are expecting arrays.

Our new code is converting from Lists (specifically ArrayLists most of the time) to arrays using List's toArray method, and i'd like to be able to skip this step.

I've seen this post which shows the implementation, but I'm not sure how it might help.

Can this be done?


No, the language specification explicitly calls out arrays separately. Arrays don't implement Iterable<T>, which is the "normal" interface used by the enhanced for loop other than for arrays. From section 14.14.2 of the JLS:

The enhanced for statement has the form:

 EnhancedForStatement:
       for ( VariableModifiers Type Identifier: Expression) Statement

The Expression must either have type Iterable or else it must be of an array type (§10.1), or a compile-time error occurs.

The two cases are then handled separately.

Converting from arrays to lists is easy of course - but it sounds like you need to do this the other way round. There's really no "pleasant" way of doing this - and creating the array requires copying everything, of course.

How much work would it be to convert at least the most heavily used bits of the API to use lists?

You can write method overloads of course, e.g.

public void foo(String[] array)
{
    foo(Arrays.asList(array));
}

public void foo(List<String> list)
{
    // Use the list
}

... but doing that for your old code will still involve work, as the real implementation is in terms of the list, not the array.


Java could have made Foo[] a subtype of Iterable<Foo>; unfortunately that won't work on primitive arrays because Java doesn't support primitive type arguments, so we don't have this nicety.


I think arrays are just special cased in the for loop's implementation.

One thing you can do is overload your methods:

public void foo(MyClass[] stuff) {
    foo(Arrays.asList(stuff));
}

public void foo(Collection<MyClass> stuff) {
    // stuff
}

Or the other way around:

public void foo(MyClass[] stuff) {
    // stuff
}

public void foo(Collection<MyClass> stuff) {
    foo(stuff.toArray(new MyClass[stuff.size()]));
}


There is not such a common interface, an Array does not implement Iterable.

What you can do is to overload you method:

public void mymethod(String ... strings) {
   mymethod(Arrays.asList(strings));
}

public void mymethod(List<String> strings) {
   // do what you need
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜