0

I am having a hard time with a piece of code that to my confidence it should work without a doubt but that is not the case.

   public static void clearUnits() {
try{
    for (int i = 1; i <= 3; i++) {

    Log.d("S.G.E", inventoryPriceUnitsList.get(i).toString());
    inventoryPriceUnitsList.remove(i);
    recipePriceUnitList.remove(i);

    }
}catch (Exception e){
  e.printStackTrace();

}

}

The purpose of this code is to run through an array list of 4 elements and remove all elements after the first element. I know this is very basic and am sorry for wasting your time but I just needed someone else to look at this because I just don't understand why it's behaving like this. the result of this code is supposed to leave an array with one element (element 0) but instead, it leaves that and also the 3rd element. I also log all elements that are supposed to be removed and it shows up properly.

1 Answer 1

2

The problem is that when you remove an element from the array, the array shifts. So let's say in first round you remove the first element, then element 1 becomes element 0, and 2 becomes 1. Now on the next round you are removing the new element 1, which was the original 2, but the original 1 remains at position 0.
The simple solution is to iterate backwards, that way you are always removing elements past the point that you are at. For example

for (int i = 3; i >= 0; i--) 

will work fine.

Sign up to request clarification or add additional context in comments.

2 Comments

WOW bro you are a god thank you, i had an idea that it was something along those lines was causing the strange behavior but just could not put my thumb on it. thanks a lot bro
am not sure how to do that, am looking around

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.