51

So in C#, I can treat a string[] as an IEnumerable<string>.

Is there a Java equivalent?

5 Answers 5

52

Iterable<String> is the equivalent of IEnumerable<string>.

It would be an odditity in the type system if arrays implemented Iterable. String[] is an instance of Object[], but Iterable<String> is not an Iterable<Object>. Classes and interfaces cannot multiply implement the same generic interface with different generic arguments.

String[] will work just like an Iterable in the enhanced for loop.

String[] can easily be turned into an Iterable:

Iterable<String> strs = java.util.Arrays.asList(strArray);

Prefer collections over arrays (for non-primitives anyway). Arrays of reference types are a bit odd, and are rarely needed since Java 1.5.

Sign up to request clarification or add additional context in comments.

3 Comments

For more info on why you cannot cast between Iterable<String> and Iterable<Object>, check out covariance and contravariance.
Okay, so now let's address the 500-lb gorilla in the room. How do you use Iterable<T>? -- what is the equivalent yield return statement in Java?
@BrainSlugs83 I think that's a different question.
10

Are you looking for Iterable<String>?

Iterable<T> <=> IEnumerable<T>
Iterator<T> <=> IEnumerator<T>

Comments

5

Iterable <T>

Comments

3

I believe the Java equivalent is Iterable<String>. Although String[] doesn't implement it, you can loop over the elements anyway:

String[] strings = new String[]{"this", "that"};
for (String s : strings) {
    // do something
}

If you really need something that implements Iterable<String>, you can do this:

String[] strings = new String[]{"this", "that"};
Iterable<String> stringIterable = Arrays.asList(strings);

Comments

0

Iterable<T> is OK, but there is a small problem. It cannot be used easily in stream() i.e lambda expressions.

If you want so, you should get it's spliterator, and use the class StreamSupport().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.