如果其他ArrayList中的条件为true,如何从ArrayList中删除项目

问题描述 投票:1回答:2

我有一个带有三列的JTable,每列都填充了一个由ArrayList组成的数组。我正在尝试创建一个搜索系统,用户将在第一列中搜索一个值,并且JTable的行将被过滤掉,这样只有包含搜索框中指定String的行才显示在按下按钮后的表格。在另一个表上,这通过过滤使用此循环使用的ArrayList来工作:

String s = searchBar.getText();
ArrayList<String> fn = new ArrayList<>();
fn.addAll(names); //names is the arraylist that contains all the values that will be filtered
for(Iterator<String> it = fn.iterator(); it.hasNext(); ) {
    if (!it.next().contains(s)) {
        it.remove();
    }

这段代码可以过滤掉数组,但我要做的是仅在其中一个ArrayLists不包含s String的情况下过滤3个ArrayLists。我试过这样做:

String s = searchBar.getText();
ArrayList<String> fn = new ArrayList<>();
ArrayList<String> fp = new ArrayList<>();
fn.addAll(names); //names is the arraylist that contains all the values that will be filtered
fp.addAll(numbers)//one of the other arraylists that I want to filter
for(Iterator<String> it = fn.iterator(), itp = fp.iterator(); it.hasNext() && itp.hasNext(); ) {
    if (!it.next().contains(s)) {
        itp.remove();
        it.remove();
    }

当我运行这段代码时,在我写“itp.remove();”的行上的线程“AWT-EventQueue-0”java.lang.IllegalStateException中得到一个Exception。有没有一种方法可以从基于其中一个的数组中删除?

java exception arraylist jtable illegalstateexception
2个回答
1
投票

我很高兴您修复了您的例外情况。无论如何,当我说回迭代时,我的意思是那样的

首先,有些检查就好

 if(fn.size()==fp.size()){
   // and after that go to delete. 
  for (int i=fn.size(); i>0;i--) { 
      if (fn.contains(s)) {
      fn.remove(i);
      fp.remove(i);
  } }}

无论如何,你和我的方法不适合多线程,因为ArrayList不是并发对象,它也是remove方法


1
投票

所以我设法通过使用ArrayList中的remove方法而不是Iterator中的remove方法来修复它。我知道这不是推荐的做法,但它似乎没有带来任何负面影响,所以我现在就保留它。我使用的代码是:

int i = 0;
for (Iterator<String> it = fn.iterator(); it.hasNext(); i++) {
    if (!it.next().contains(s)) {
        it.remove(); //Iterator's remove
        fp.remove(i);// ArrayList's remove which avoids the error
    }
}

感谢所有帮助过的人

© www.soinside.com 2019 - 2024. All rights reserved.