Search code examples
javajlistselectedindices

Loop through jList indices to remove items


i try to loop through indices of my selected items in a jList to remove them.

int[] indexoptio;
    indexoptio = this.list_optio.getSelectedIndices();

    for (int i=0; i<indexoptio.length ; i++) {
        this.optio.remove(indexoptio[i]);}
    this.list_optio.setModel(optio);

It works perfect except when i only have 2 items in my list. When i select both items it only removes one of them...


Solution

  • This will be because changing a datastructure while working on a set of indexes referring to it unchanged. This is easier shown using an example. Say you have a list items with 3 elements:

    ["item1", "item2", "item3"]
    

    And you want to remove items 1 and 3, using your code above what you're actually doing is:

    items.remove(0);
    items.remove(2);
    

    After the first removal, the list has become this:

    ["item2", "item3"]
    

    See how "item3" is now at position 1 whereas previously it was at position 2?

    Your list of selected indices refer to the original list of data, but after the first delete list has changed.

    I think the following should work for you:

    int[] indexoptio;
    indexoptio = this.list_optio.getSelectedIndices();
    
    for (int i=0 ; i<indexoptio.length ; i++) {
        this.optio.remove(indexoptio[i]-i);
    }
    this.list_optio.setModel(optio);
    

    Every iteration the original list has decreased in size by 1 and some elements have shifted down, so by subtracting the loop counter (indexoptio[i]-i) it should keep the values in sync