foreach
code block. It works pretty simple, just provide an array or collection then provide a variable to store each element into then you'll be able to go through each element that easy:int[] myArray = new int[] { 2, 3, 5, 7, 11, 13 }; foreach (int i in myArray) { System.Console.WriteLine(i); }In Java, however, it wasn't that easy. Before Java 1.5, to be able to go through each element of an array you will have to set an initial value, terminating test value, and then an increment statement:
int[] myArray = {2, 3, 5, 7, 11, 13}; for(int i=0; i<myArray.length; i++) { System.out.println(myArray[i]); }When Java realized that C# is gaining some edge they released Java 1.5 with all the collection classes and the enhancement of for loop to handle foreach activities. Now, looping through an array or collection can be done in Java just as easy as you do it in C#:
int[] myArray = {2, 3, 5, 7, 11, 13}; for(int i : myArray) { System.out.println(i); }Do take note, however, that this for-loop structure will not work on Java 1.4 and lower. And if you're using those versions of Java then you have to use the 1st Java code block that's presented here.
I hope that you learned something new today!
1 comment:
I think dynamic languages do this better:
PHP:
foreach($array as $value) {
echo $value;
}
Python:
for i in ls:
print i
Not to mention you don't have to revert to the ugly syntax if you also want to get the keys:
PHP:
foreach($array as $key => $value)
{
echo $key . ": " . $value;
}
Python:
for k,v in enumerate(ls):
print "{0}:{1}".format(k,v)
Cheers to the blog! Keep up the good work!
Post a Comment