BigBug
BigBug

Reputation: 6290

how to loop through a list of byte arrays...?

if i have a list of byte arrays, and i want to delete an array if the first index is a specific value, how would i use something like this:

bytearrays.removeAll(Collections.singletonList(-7));

if this is not possible, what would be the best way to go about this? I've tried using iterators, but i don't think i understand them enough to be able to force it to check the first index of each array in the list of arrays...

when i simply create a for loop, for some reason some of the arrays are not deleted(usually the last array, sometimes the last 2 depending on how many arrays).

Upvotes: 1

Views: 6661

Answers (3)

jack smith
jack smith

Reputation: 711

You are not supposed to remove from a List while iterating it cause removing an entry cause the List to change - it shifts the rest of the list, so also the size of the list changes. You better use an Iterator to remove. Anyway, pay attention that if you iterate over in with a loop that its stop-condition is on the list's length then consider that it changes. This is also resolved by the hasNext() method of Iterator.

Upvotes: 0

Andrzej Doyle
Andrzej Doyle

Reputation: 103797

The majority of lists have an iterator that correctly implements the remove method.

Given that the simplest solution would be something like the following:

final Iterator<byte[]> iter = bytearrays.iterator();
while (iter.hasNext()) {
    final byte[] temp = iter.next();
    // TODO check for zero-length arrays
    if (temp[0] == -7) {
        iter.remove();
    }
}

Upvotes: 4

Aleks G
Aleks G

Reputation: 57316

Your main issue is that you're looping from the first to the (last-2) element in the array, but when you delete an element, all other elements shift. Instead, you should loop in the reverse order:

for(int z = bytearray.size() - 1; z >=0 ; z--)
{
    byte[] temp = bytearrays.get(z);
    if(temp[0] == -16 || temp[0] == -11 || temp[0] == -7)
    {
        bytearrays.remove(z); 
    }
}

I'm not sure why you're removing the first element of the array regardless of other conditions, but you can add that line before the loop, if you need to.

Upvotes: 2

Related Questions