I iterate through an ArrayList this way:
for (T t : list){
...
}
When I did this, I never thought I had to access the previous and next elements of this element. Now my code is huge. It costs a lot if I rewrite it with:
for (int i = 0; i < list.size(); i++){
...
}
No, the for-each loop is meant to abstract the Iterator<E>
which is under the hood. Accessing it would allow you to retrieve the previous element:
ListIterator<T> it = list.listIterator();
while (it.hasNext()) {
T t = it.next();
T prev = it.previous();
}
but you can't do it directly with the for-each.
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