javalistchangelist

How to dynamically change list


What I mean is that I'm given an array of objects and if my list which I'm going to change doesn't have some objects from the given list then I add them to mine, if my list does have some objects that the given list doesn't then I remove them from my list. I've tried to implement this, but it didn't work.

void changeList(String data){
    String[] elements = data.split(":");
    for (int i = 0; i < elements.length - 1; i++) {
        if(i < listOfUsersModel.size() && !listOfUsersModel.getElementAt(i).equalsIgnoreCase(elements[i+1])){
            listOfUsersModel.remove(i);
            listOfUsersModel.addElement("<html>" + elements[i+1] + "</html>");
        } else if (i >= listOfUsersModel.size()){
            listOfUsersModel.addElement("<html>" + elements[i+1] + "</html>");
        }
    }
}

And yeah, the first element in elements will always be LIST, I just need it to specify if that's a list or something else. P.S. ListOfUsersModel is a DefaultListModel object.


Solution

  • I can see some problems in your code:

    1. You have an array of strings (produced by the split) and a list. You are using the indexes for the array as indexes for the list. That means you will only remove matching elements from the list if they have the same index as in the array. That does not match your description of what you are trying to do.

    2. When you remove an element from a list, all elements after the removed element move to a different position; i.e. removeElement(i) causes element i+1 to move to position i, element i+2 to move to i+1 and so on. But ... then you increment i !!

    3. The addElement adds an element at the end of the list.

    If you plan to remove / replace all element that match, you need a nested loop. Also, look at the setElement and insertElement methods for the class that you are using. (You are clearly using methods that are not in the List API ... but I can't figure out which API it is.)

    Finally, I don't see where you attempt to do this:

    ... if my list does have some objects that the given list doesn't then I remove them from my list.

    To do that, you will need to make a second pass, with another pair of nested loops ...