javasortingdefaultlistmodel

Sorting a List Model in descending order Java


I'm trying to sort a list model by splitting a string comparing the id's i have assigned to any given index and comparing it to another index, it works the first time I press the button however, if I press the button again it moves two indexes out of order.

Any help would be appreciated, if you need anything from me - please ask

An example of the string I'm splitting:

DRAMA,Harry Potter,2,5698750,J.K Rowling,500,08/12/2004,Lyle,0,0

The code that is giving me trouble

public void sortByID()
    {
        DefaultListModel tmp = new DefaultListModel();  
        for(int x = 0; x < listModel.size(); x++)
        {
            String[] a = listModel.get(x).toString().split(",");

            for(int y = 0; y < listModel.size(); y++)
            {
                String[] b = listModel.get(y).toString().split(",");

                if(a[2].compareTo(b[2]) > 0 && a[1].equals(b[1]) != true)
                {
                    tmp.add(0, listModel.get(y));
                    listModel.set(y, listModel.get(x));
                    listModel.set(x, tmp.get(0));
                }
            }
        }
    }

Solution

  • One problem with that solution:
    testing if compareTo returns a positive value, no matter if x is smaller or greater than y.
    Example, suppose we only have 2 ids ordered like ["2", "1"] - if x=0, y=1 "2".compareTo("1") will return >0 so both values are swapped resulting in ["1", "2"].
    Some iterations later, x=1, y=0 so id[x]=="2", id[y]=="1", comparing ("2".compareTo("1")) will again return >0 and the values will be swapped again.

    Solution: y should always be greater (or always smaller) than x (e.g. for (int y = x + 1; ...)

    Using a debugger and executing step-by-step should help seeing what is happening...