I have the following code running, but I sometimes get some sort of concurrency exception when running it.
ArrayList<Mob> carriers = new ArrayList<Mob>();
ArrayList<Mob> mobs = new ArrayList<Mob>();
...
for (Mob carrier : carriers){
for (Mob mob : mobs){
checkInfections (carrier, mob);
}
}
I refactored it to solve the concurrency problem, but it did lead me to a question. Would there be a difference in performance if I change the for construct to an Iterator pattern? What’s the access level difference between the foreach construct and the Iterator class?
The difference is largely syntactic sugar except that an
Iteratorcan remove items from theCollectionit is iterating. Technically, enhancedforloops allow you to loop over anything that’sIterable, which at a minimum includes bothCollections and arrays.Don’t worry about performance differences. Such micro-optimization is an irrelevant distraction. If you need to remove items as you go, use an
Iterator. Otherwiseforloops tend to be used more just because they’re more readable ie:vs: