Java Arrays & Generics : Java Equivalent to C# IEnumerable

前端 未结 5 1080
小鲜肉
小鲜肉 2020-12-15 15:12

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

Is there a Java equivalent?

5条回答
  •  庸人自扰
    2020-12-15 15:58

    Iterable is the equivalent of IEnumerable.

    It would be an odditity in the type system if arrays implemented Iterable. String[] is an instance of Object[], but Iterable is not an Iterable. 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 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.

    提交回复
    热议问题