1

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).

1
  • 1
    You are changing the size when you remove things from it, but you don't change the size Commented Mar 8, 2012 at 10:31

3 Answers 3

4

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

this answer is pretty kick ass. didn't think of user byte[] temp this way... pretty neat. thanks man. +1 and best answer
2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.