This is my Java code:
List<Object> objects = new ArrayList();
// Assign values to objects
...
for (int i = 0; i < objects.size(); i++) {
Object object = objects.get(i);
...
}
I have two questions:
- Is
objects.size()calculated only once before stating the loop, or is it calculated each loop? - If
objects.size()is calculated each loop, then if other thread change it at the same time without multi-threads protection, the code may be crashed.
Am I correct?
Answers:
objects.size()is called every loop (whether it is calculated depends on the ArrayList implementation, which you shouldn’t care about)Real answer:
You shouldn’t have to care, and here’s how you don’t have to:
foreachsyntax, which means you don’t have to use an index etc – it’s done for you: