有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在其他ArrayList中的条件为true时从ArrayList中删除项

我有一个包含三列的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();
    }

这段代码用于过滤掉数组,但我试图做的是仅基于其中一个ArrayList不包含s字符串的情况过滤3个ArrayList。 我试着这样做:

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

当我运行这段代码时,我在线程“AWT-EventQueue-0”java中得到一个异常。在我写“itp.remove();”的行上的lang.IllegalStateException。 是否有一种方法可以仅基于其中一个从两个阵列中删除


共 (2) 个答案

  1. # 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方法

  2. # 2 楼答案

    因此,我设法通过使用ArrayList中的remove方法而不是迭代器中的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
        }
    }
    

    感谢所有帮助过你的人