Ameer Brima
Ameer Brima

Reputation: 1

How to remove() a sequence of String elements in an ArrayList() using indices in java?

I want to remove the 4 indices in sequence string elements in my code here. My ArrayList contains multiple String elements:

{MyString,MyString1,MyString2,MyString3,MyString4,...., MyString10}

This is my code:

String removedItem = "MyString";

for (int i = 0; i < myArrayList.size(); i++) {  
    if (myArrayList.get(i).equals(removedItem)) {
        myArrayList.remove(i);
        myArrayList.remove(i+1);
        myArrayList.remove(i+2);
        myArrayList.remove(i+3);
    }
}

System.out.println(myArrayList);

My code doesn't seem to remove the first 4 indices in order. What am I doing wrong and how do I do fix it? Any help will be greatly appreciated!

Upvotes: 0

Views: 629

Answers (3)

Mimu Saha Tishan
Mimu Saha Tishan

Reputation: 2633

String removedItem = "MyString";

int remove = 0;
for (int i = 0; i < myArrayList.size(); i++) {  
    if (myArrayList.get(i).contains(removedItem)) {
        myArrayList.remove(i);
        i--;
        remove++;
        if(remove == 4) {
            System.out.println(myArrayList);
            return;
        }
    }

}

If you change your myArrayList value and removedItem value it will work also.

Upvotes: 0

Sherif Abdelkhaliq
Sherif Abdelkhaliq

Reputation: 150

Because when with each remove call the size of the list will be decreased by one. To trace this you can use breakpoints at remove calls.

For example, if your ArrayList is initialized with 4 elements. {MyString,MyString1,MyString2,MyString3}

when i = 0:

  • After calling myArrayList.remove(0); MyString will be removed and the size of myArrayList will be 3 {MyString1,MyString2,MyString3}.

  • After calling myArrayList.remove(1); this will remove the MyString2 not MyString1 {MyString1,MyString3}.

  • myArrayList.remove(2); this will throw Exception

You can use Iterator and safely check with hasNext() method or use the code provided by Mr.HE answer and safely check that elemnt != null before removing it.

Upvotes: 0

Mr.HE
Mr.HE

Reputation: 21

If you want to delete the specified value and the next three elements.You can use this:

for (int i = 0; i < myArrayList.size(); i++) {  
    if (myArrayList.get(i).equals(removedItem)) {
        myArrayList.remove(i);
        myArrayList.remove(i);
        myArrayList.remove(i);
        myArrayList.remove(i);
    }
}

Because every time you delete an element, the next element moves forward.

Upvotes: 2

Related Questions