简体   繁体   中英

loop not iterating through entire arraylist

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 calling test.remove(i) which is shorting the array by one every iteration. Your loop is essentially doing this:

  1. i = 0 size = 5 Keep going

  2. i = 1 size = 4 Keep going

  3. i = 2 size = 3 Keep going

  4. 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:

while(!eateriesListDefault.isEmpty()) {
   MyLog.e(TAG, "Name " + test.get(0).getName());
   test.remove(0);
}

Your second loop removes elements from the array while your loop index continues to increase. On the fourth pass, your loop index is 3, but eateriesListDefault.size is 2, so the loop exits.

Try this instead:

for ( Iterator<Eatery> it = test.iterator(); it.hasNext(); ) {
   MyLog.e(...)
   it.remove();
}

The behavior of an iterator is unspecified if the list is modified during iteration in any way other than by calling Iterator.remove(). See the Iterator.remove() documentation .

Also, you may want to make a copy of the default list. Your "test =" statement is just making a new reference to the same list.

test = new ArrayList<Eatery>( eateriesListDefault ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM