java - Can program execution go different by choosing between Enhanced for loop and old fashioned index based loop for a collection? -
i asked in interview. said no. interviewer did not seem impressed.
any corner case missed?
note: not talking cases 1 can iterate 2 times faster/modify loop variable.
in other words difference between
for (int = 0;i<set.size();i++) { // }
and
for (int x : set) { // something. }
anything performance(i know both compile same code)/etc.
the answer is: yes, program may behave differently.
kayaman mentioned thread-safety in answer. special case may show different behavior. question whether or not collection itself modified during iteration 1 aspect may influence program flow.
but regardless of that, enhanced for-loop, iterator created @ beginning of loop. , iterator keep reference "his" collection iterating over. in contrast that, iteration classical for-loop take account when collection replaced new one.
this can seen in following example.
import java.util.arraylist; import java.util.list; public class differentforloops { public static void main(string[] args) { differentforloops d = new differentforloops(); d.startold(); d.startnew(); } private list<integer> list; private void createlist(int size) { list = new arraylist<integer>(); (int i=0; i<size; i++) { list.add(i); } } public void startold() { createlist(10); (int = 0;i<list.size();i++) { system.out.println("old: entry "+list.get(i)+" of "+list); pause(); list = list.sublist(0, list.size()-1); } } public void startnew() { createlist(10); (int : list) { system.out.println("new: entry "+a+" of "+list); pause(); list = list.sublist(0, list.size()-1); } } private static void pause() { try { thread.sleep(500); } catch (interruptedexception e) { thread.currentthread().interrupt(); } } }
Comments
Post a Comment