what is the difference between executing For loop Java -
could tell me, difference between loop java in code , b? while both of them gives same result in executing? , know doing, why loop written way in code *a* thanks
the code
//code public class myarray { public static void main (string[] args){ int[] ={1,10,30,40,50}; (int : a) { system.out.println(i); } } } //==================================== //code b public class myarray{ public static void main (string[] args){ int[] ={1,10,30,40,50}; (int i=0;i< a.length; i++) { system.out.println(a[i]); } } }
iterating on collection uglier needs be. consider following method, takes collection of timer tasks , cancels them:
void cancelall(collection<timertask> c) { (iterator<timertask> = c.iterator(); i.hasnext(); ) i.next().cancel(); }
the iterator clutter. furthermore, opportunity error. iterator variable occurs 3 times in each loop: 2 chances wrong. for-each construct gets rid of clutter , opportunity error. here how example looks for-each construct:
void cancelall(collection<timertask> c) { (timertask t : c) t.cancel(); }
for each better way of iterating.
limitation: in for-each loop not able know number of element(index of element in collection) processing, need define counter same, while in simple loop i
tells number of element processing.
Comments
Post a Comment