-3

I've been trying so far to write a method ,removeEvenLength that takes an ArrayList of Strings as a parameter and that removes all of the strings of even length from the list. But so far I've been getting a IndexOutOfBoundsException and I don't know why.

Any help would be appreciated

public static ArrayList<String> removeEvenLength(ArrayList<String> list) {
int size = list.size();
ArrayList<String> newLst = new ArrayList<String>();

for (int x = 0; x < size; x++) {
    if (list.get(x).length() % 2 == 0) {
        list.remove(x);
    }
}

return list;

}

Matthew
  • 29
  • 3

2 Answers2

1

Once you remove an element, the size of the list reduces by one and hence the variable size no longer denotes the true size of the list

Also, after you remove a String at index i, the elements from i+1, i+2.. list.size() - 1 will be moved to the left by one position. So, incrementing the loop counter x all the time is wrong and you will skip some elements.

Here's a way to do it right

for (int x = 0; x < list.size();) {
    if (list.get(x).length() % 2 == 0) {
        list.remove(x);
    } else {
        x++;
    }
}
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
0
public static List<String> removeEvenLength(List<String> list) { 
 List<String> newList = new ArrayList<String>();
 for (String item: list) { 
       if (item.length % 2 != 0) {
             newList.add(item); 
        }
  }
 return newList;
}
dryleaf
  • 415
  • 3
  • 18