I’m having a problem where I am trying to iterate through an arraylist which stores restaurant objects but the loop only goes through 3 of the five elements.
I created a test method to illustrate:
public void testLoop() {
ArrayList<Eatery> test = new ArrayList<Eatery>();
test = eateriesListDefault;
for(Eatery e : test) {
MyLog.e(TAG, "Name: " + e.getName());
}
for (int i = 0; i < eateriesListDefault.size(); i++) {
MyLog.e(TAG, "Name " + test.get(i).getName());
test.remove(i);
}
for(Eatery e : test) {
MyLog.e(TAG, "Name " + e.getName());
}
}
Here test will have 5 eatery objects in it. The first loop succesfully prints 5 of 5 names.
The second loop only removes 3 of the eateries and therefore the last loop prints two names.
I have tried using
for(Eatery e : eateriesListDefault) {
MyLog.e(TAG, "Name: " + e.getName());
test.remove(e);
}
in place of the second loop, however I get a concurrent access error.
Does anyone know what I am doing wrong?
You’re calling
eateriesListDefault.size()in each loop iteration. At the same time, you’re callingtest.remove(i)which is shorting the array by one every iteration. Your loop is essentially doing this:i = 0
size = 5
Keep going
i = 1
size = 4
Keep going
i = 2
size = 3
Keep going
i = 3
size = 2
stop
If you’re goal was to print out the first element of the array then remove it, you could probably get there by this loop: