Java Arrays & Generics : Java Equivalent to C# IEnumerable<T>

五迷三道 提交于 2019-11-27 17:05:08

问题


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

Is there a Java equivalent?


回答1:


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.




回答2:


Are you looking for Iterable<String>?

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



回答3:


Iterable <T>




回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/362367/java-arrays-generics-java-equivalent-to-c-sharp-ienumerablet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!