删除数组列表中的每个第二个元素

时间:2018-04-01 06:15:50

标签: java

到目前为止,我一直在尝试编写一个方法,removeEvenLength,它将String的ArrayList作为参数,并从列表中删除所有偶数长度的字符串。但到目前为止,我一直得到一个IndexOutOfBoundsException,我不知道为什么。

任何帮助将不胜感激

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;

}

2 个答案:

答案 0 :(得分:1)

删除元素后,列表的大小减1,因此变量size不再表示列表的真实大小

此外,在索引i处删除字符串后,i+1, i+2.. list.size() - 1中的元素将向左移动一个位置。因此,一直递增循环计数器x是错误的,您将跳过一些元素。

这是一种正确的方法

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

答案 1 :(得分: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;
}
相关问题