Is the loop condition calculated each loop for “for” sentence in Java?-Collection of common programming errors
Notionally the objects.size() could be evaluated on each loop. However, as the method is short it can be inlined and cached as its not a volatile variable. i.e. another thread could change it but there is no guarantee that if it did you would see the change.
A short way to save the size is to use the follow.
for (int i = 0, size = objects.size(); i < size; i++) {
Object object = objects.get(i);
...
}
However if you are concerned that another thread could change the size, this approach only protects you if an object is added. If an object is removed you can still get an exception when you attempt to access the value which is now beyond the end of the list.
Using a CopyOnWriteArrayList avoids these issues (provided you use an Iterator) but makes writes more expensive.