Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove a string from an array list

I keep getting this error:

java.lang.IndexOutOfBoundsException: Index: 3, Size: 3

I am trying to remove the string "Meg", and it will compile, but I keep getting this error.

import java.util.ArrayList;

public class CustomerLister2 {
    public static void main (String[] args) {

        ArrayList<String> name = new ArrayList<String>();

        name.add("Chris");
        name.add("Lois");
        name.add("Meg");
        name.add("Meg");
        name.add("Brain");
        name.add("Peter");
        name.add("Stewie");

        for ( int i = 0;  i < name.size(); i++){
            name.get(i);
            name.remove(i);
            name.set(i,"Meg");
        }

        for(String names: name){
            System.out.println(names);
        }
    }
}
like image 653
user2872881 Avatar asked Feb 20 '26 09:02

user2872881


1 Answers

if you want to remove "Meg" then use this

import java.util.ArrayList;

public class CustomerLister2 {
    public static void main (String[] args) {

        ArrayList<String> name = new ArrayList<String>();

        name.add("Chris");
        name.add("Lois");
        name.add("Meg");
        name.add("Meg");
        name.add("Brain");
        name.add("Peter");
        name.add("Stewie");


        for ( int i = 0;  i < name.size(); i++){
            String tempName = name.get(i);
            if(tempName.equals("Meg"){
                name.remove(i);
            }
        }

        for(String names: name){
            System.out.println(names);
        }
    }
}
like image 95
Mohsin AR Avatar answered Feb 22 '26 23:02

Mohsin AR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!