首页 > 解决方案 > java - 如何使用java中的索引删除()ArrayList()中的字符串元素序列?

问题描述

我想在我的代码中删除序列字符串元素中的 4 个索引。我的 ArrayList 包含多个 String 元素:

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

这是我的代码:

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);

我的代码似乎没有按顺序删除前 4 个索引。我做错了什么,我该如何解决?任何帮助将不胜感激!

标签: javastringarraylistindexing

解决方案


如果你想删除指定的值和接下来的三个元素。你可以使用这个:

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);
    }
}

因为每次删除一个元素,下一个元素都会向前移动。


推荐阅读