0

I am trying to sort an EList of functions by using Java's Comparator, but the list is not sorted after calling sort().

The way I implement it is this:

//Func.xtend <-- Start -->

public class NameComparator implements Comparator<Function_Name> {  
    override int compare (Function_Name function1, Function_Name function2)
    {
        return function1.func.compareToIgnoreCase(function2.func)
    }
}

public class CheckNames {   
    def void checkDuplicateNames(Main_func para_func) {
        var EList<Function_Name> functions = para_func.getContains()        
        var NameComparator pc = new NameComparator()

        functions.sort(pc) //<-- sorting here

        var Iterator<Function_Name> oIt = functions.iterator ()
        while (oIt.hasNext)
        {           
            var Function_Name func = oIt.next   ()
            System::out.println(func.func.toString)
        }
    }
}

// <-- End -->

Am I doing something wrong? Theoretically, after calling functions.sort(pc), the contents in variable "functions" should already be sorted, right? Or do I still need to do some processing?

chris yo
  • 1,187
  • 4
  • 13
  • 30

1 Answers1

3

As far as I know, List::sort in Xtend doesn't sort in-place, but returns a new sorted list. So you have to call List::sortInPlace instead.

Apart from this, you might run into problems when you try to sort unique ELists (for example, containments) in-place. During the sort operation (Xtend actually calls java.util.Collections.sort for this), some elements may temporarily be contained twice in the list. However, unique lists check for duplicates and throw an IllegalArgumentException when you try to add an element a second time (see AbstractEList.set(in, E)). To avoid this, you should sort unique ELists like this:

var sortedFunctions = functions.sort(pc)
functions.clear()
functions.addAll(sortedFunctions)
Andreas Mayer
  • 687
  • 5
  • 15