Java Arraylist通过索引删除多个元素

Lit*_*ita 5 java android arraylist stop-words

这是我的代码:

for (int i = 0; i < myarraylist.size(); i++) {
        for (int j = 0; j < stopwords.size(); j++) {
            if (stopwords.get(j).equals(myarraylist.get(i))) {
                myarraylist.remove(i);
                id.remove(i);
                i--; // to look at the same index again!
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我有问题..删除元素后,所有索引总是改变,上面的循环太乱了.

为了说明:我有54个数据,但上面的循环在元素删除后变得混乱..因此只检查了50个数据.

有没有其他方法或修复我的代码以索引删除多个元素?元素索引对我来说非常重要,要删除具有相同索引的另一个arraylist.

Ste*_*Kuo 10

用于Iterator.remove()在迭代时删除元素.

for (Iterator<String> iter = myarraylist.iterator(); iter.hasNext(); ) {
  String element = iter.next();
  if (element meets some criteria) {
    iter.remove();
  }
}
Run Code Online (Sandbox Code Playgroud)

或者使用Google Guava的过滤器,该过滤返回过滤后的视图并保持原始列表不变.

Iterable<String> filtered = Iterables.filter(myarraylist, new Predicate<String>() {
  public boolean apply(String element) {
    return true of false based on criteria
  }
});
Run Code Online (Sandbox Code Playgroud)


Ung*_*uer 7

你需要记住的一件事是,当你使用ArrayLists它时,它们意味着多才多艺,而不是Arrays.您可以通过删除整个索引,为其添加索引以及执行精彩来缩短数组ArrayLists.

对于那些没有意识到或记住,当你删除一个值,ArrayList索引(或任何正确的复数)重新调整和ArrayList缩短时,这是一个常见的问题.

在尝试从a中删除元素时ArrayList,应始终从结尾处开始ArrayList.

for(int x = arrayList.size() - 1; x > 0; x--)
{
    arrayList.remove(x);
}
Run Code Online (Sandbox Code Playgroud)

这应该为您提供您正在寻找的功能.看看ArrayList API,了解可能对您有帮助的其他方法.