I wonder if there is a difference between these:
ArrayList<Example> list = new ArrayList<Example>
1-)
for(int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
2-)
for(Example example : list) {
example.doSomething();
}
If there is not any difference which one is more common or efficient?
The traditional for loop in Apex corresponds to the traditional syntax used in Java and other languages. Its syntax is: for (init_stmt; exit_condition; increment_stmt) { code_block }
The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more readable. It is known as the for-each loop because it traverses each element one by one. The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order.
for (int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
RandomAccess
lists
LinkedList
in every iteration of the loop, get(i)
will have to iterate over all elements starting from head/tail
to i
List
since List#get(int)
is usedi = 0;
instead of int i = 0;
- will refer to variable declared before the loop, possible side effects outside of the loop>
instead of <
- loop will not executej++
instead of i++
- infinite loop.get(j)
instead of .get(i)
- will always get the same elementfor (Example example : list) {
example.doSomething();
}
ConcurrentModificationException
Iterator
specific for the collection
LinkedList
Collection
, but with every Iterable
since Iterable#iterator()
is used
List
with a Set
- no changes to the loop requiredIterable
for-each
loop wins with a score 3 : 2.
The only reason to use a traditional loop is when:
They are basically the same, but for-each (the second one) has certain restrictions.
It can be used for accessing the array elements but not for modifying them.
It is not usable for loops that must iterate over multiple collections in parallel—for example, to compare the elements of two arrays.
It can be used only for a single element access and cannot be used to compare successive elements in an array. It is a forward-only iterator. If you want to access only a few elements of the array, you would need to use the traditional for loop.
The second one works with every type of (potentially unordered) Iterable, as it doesn't rely on random access, i.e. get(i)
.
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