【问题标题】:How to remove item from ArrayList if condition in other ArrayList is true如果其他 ArrayList 中的条件为真,如何从 ArrayList 中删除项目
【发布时间】:2019-04-20 11:46:18
【问题描述】:

我有一个包含三列的 JTable,每一列都填充了一个由 ArrayList 组成的数组。我正在尝试创建一个搜索系统,用户将在第一列中搜索一个值,而 JTable 的行将被过滤掉,因此只有包含搜索框中指定字符串的行才会显示在按下按钮后的表格。在另一个表上,这通过使用此循环过滤使用的 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 字符串的情况下过滤 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 中得到一个异常。 有没有一种方法可以仅基于其中一个从两个数组中删除?

【问题讨论】:

  • 在循环中也添加itp.next()
  • 您不能迭代和删除元素。它不同步。但是您可以从列表开始删除 while 循环
  • 如果我是你,我会采用 OOP 方法,而不是使用三个并行的 List,而是构造一个对象来保存信息并拥有一个列表
  • @GBlodgett 我之所以这样是因为数据是从 sql 数据库中获取的,而且我真的不知道有其他方法可以做到这一点,哈哈
  • @Dred 对不起,我不太明白你的意思

标签: java exception arraylist jtable illegalstateexception


【解决方案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 不是并发对象,它也是删除方法

【讨论】:

    【解决方案2】:

    所以我设法通过使用 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
        }
    }
    

    感谢所有帮助过的人

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2015-05-23
      相关资源
      最近更新 更多