0
What is enchanced loop plz explain me in detail
corejava
2 ответов
+ 12
The enhanced for loop (sometimes called a "for each" loop) is used to traverse elements in arrays. The advantages are that it eliminates the possibility of bugs and makes the code easier to read. Example :
int[ ] primes = {2, 3, 5, 7};
for (int t: primes) {
System.out.println(t); }
It declares a variable of a type compatible with the elements of the array being accessed. The variable will be available within the for block, and its value will be the same as the current array element.
So, on each iteration of the loop, the variable t will be equal to the corresponding element in the array.
+ 3
The enhanced for loop uses the Itterator class to itterate through elements in a Collection or Array.
It is better to use the enhanced loop rather than the regular for loop when casting is involved. This is because the enhanced for loop will basically cast for you, extracting all elements of the specified type.
Example/
Animals[] array = {Tiger, Lion};
for (Cat i : array)
i.doStuff();
Instead of:
for(int i = 0; i < array.length; i++)
((Cat)array[i]).doStuff()
// Lets assume everything in the array can be casted to a Cat
It also has the advantages @Dayve brought up.