Home » Java » foreach VS for

foreach VS for

today, the interviewer asked, "

!"

java in the array and linked list, traversal, foreach and for loop choose which
?
Usually, I didn't notice the difference between foreach and for loop. I thought it was the same, but since the interviewer asked, it must be different,.


refer to this link .,

Foreach, that is, The, enhanced, for, statement, and when using foreach, there are only two instances of objects that are traversed:


1. class that inherits the Iterable interface

at this point, foreach runs

in the following manner
for (I, #i = Expression.iterator (); #i.hasNext (); {)
{VariableModifier}, TargetType, Identifier = (TargetType) #i.next ();
Statement
}

here's one thing to note:


If the declared type of the local variable in the header of the enhanced for statement is a reference type, then TargetType is that declared type otherwise, TargetType is the; upper bound of the capture conversion of the type argument of I, or Object if I is raw.

The effect is that if the first variable in foreach is a reference type, then TargetType declares that type, or TargetType declares the type.

of the Iterator.next object

, for example, is the following example:


List<, extends, Integer>, l =...
for (float I: l)...
Equivalent to
for (Iterator, #i = l.iterator (); #i.hasNext (); {)
float #i0 = (Integer) #i.next ();
...

2. array

when the object traversed is an array, foreach runs

in the following manner
T[] #a = Expression; 
L1:, L2:, ... , Lm:
for (int, #i = 0, #i, < #a.length, #i++) {
{VariableModifier}, TargetType, Identifier = #a[#i];
Statement
}

back to the beginning of the problem, in traversing arrays, using the for and foreach are the same, but the use of linked list (such as LinkedList), using the foreach performance will be better, after all, the list is longer than the insert delete, positioning is not as good as the access array.


note: if there is an error above, look hesitate to place
!
Please indicate the source: http://blog.csdn.net/big_heart_c/article/


Latest