Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Is there a Java equivalent?

like image 563
Winston Smith Avatar asked Dec 12 '08 10:12

Winston Smith


People also ask

What are Java array types?

Output. Multi-dimensional array − A multi-dimensional array in Java is an array of arrays. A two dimensional array is an array of one dimensional arrays and a three dimensional array is an array of two dimensional arrays.

What is array in Java with example?

An array is a collection of similar types of data. For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names. String[] array = new String[100]; Here, the above array cannot store more than 100 names.

What is array in Java for beginners?

Arrays can have data items of simple types such as int or float, or even user-defined datatypes like structures and objects. The common data type of array elements is known as the base type of the array. Arrays are considered as objects in Java. The indexing of the variable in an array starts from 0.

How do you declare an array in Java?

The syntax for declaring an array is: datatype[] arrayName; datatype : The type of Objects that will be stored in the array eg. int , char etc.


2 Answers

Are you looking for Iterable<String>?

Iterable<T> <=> IEnumerable<T> Iterator<T> <=> IEnumerator<T> 
like image 29
bruno conde Avatar answered Sep 20 '22 03:09

bruno conde


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.

like image 164
Tom Hawtin - tackline Avatar answered Sep 23 '22 03:09

Tom Hawtin - tackline