0

If I remove an element from a list, do all the elements to the right of it shift left?

List<Integer> ints = [1,2,3,4,5];

ints.remove(0);


printf( ints[0] ) --> 2;
3

The closest you're probably going to get here is looking through documentation on Java classes to see which list-like structures there are, and how they're implemented. In the end, though, this level of detail doesn't really matter all that much to us.

The effect is that when you remove element i from a list, all indices index > i are decremented.

If you debug list[1], then remove(0), then debug list[0], you'll find that the indices have indeed "shifted". If you rely too much on that mental model, though, you'll probably end up writing fragile code.

  • 1
    N.B. often, the best strategy is to process the list backwards to remove element(s) – cropredy Nov 13 at 0:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.