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:
objects.size()
calculated only once before stating the loop, or is it calculated each loop?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?
A for loop works as long as the condition is true. The flow of control, at first comes to the declaration, then checks the condition. If the condition is true, then it executes the statements in the scope of the loop. At last, the control comes to the iterative statements and again checks the condition.
Condition is an expression that is tested each time the loop repeats. As long as condition is true, the loop keeps running. Increment is an expression that determines how the loop control variable is incremented each time the loop repeats successfully (that is, each time condition is evaluated to be true).
Yes, it is calculated each time. If you have another thread altering the size of your objects list, the loop condition will keep changing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With