Search code examples
javaexceptionarraylistjtableillegalstateexception

How to remove item from ArrayList if condition in other ArrayList is true


I have a JTable with three columns, each of which is filled with an array made from an ArrayList. I am trying to make a search system, where the user will search for a value in the first column, and the rows of the JTable will filter out, so that only the rows that contain the specified String from the search box show up on the table after a button is pressed. On another table, this worked by filtering the ArrayList used using this loop:

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

This code works to filter out the array, but what I am trying to do is filter 3 ArrayLists based on only if one of the ArrayLists does not contain the s String. I tried doing this:

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

When I run this code I get a Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException on the line where I write "itp.remove();". Is there a way I can remove from both the arrays based on only one of them?


Solution

  • I'm happy that you fix your exception. Anyway, when I said about back iteration I meant something like that

    Firstly, Some of check like

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

    Anyway, your and my method isn't good for multithreading, because ArrayList doesnt't concurrent object also it's remove method