Sorting using the comparator as the default method in the iterable interface

I am trying to write a sorting method in an interface that extends Iterable<T>, but it does not work, I think it is “logically” correct, but does not replace elements. The interface used to create the list is very similar to the one in Java, and my goal is to create a class inspired by LinkedList so that it has a ListIterator. Any suggestions? Here's the method code:

default void sort(Comparator<T> c){
    ListIterator<T> lit = listIterator();
    boolean scambio = true;
    while(scambio){
        scambio = false;
        T n1 = null;
        T n2;
        if(lit.hasNext())
            n1 = lit.next();
        while(lit.hasNext()){
            n2 = lit.next();
            if(c.compare(n1,n2) > 0){
                T tmp = n2;
                n2 = n1;
                n1 = tmp;
                scambio = true;
            }
            n1 = n2;
        }
        lit = listIterator();
    }
}
+4
source share
1 answer

You can use Collections.sort to efficiently sort your items:

Collections.sort(lit, new Comparator<T>()   {
    @Override
    public int compare(T n1, T n2)    {
        // You may use any logic here considering n1 and n2
        return n1.compare(2n);
    }
}
+1
source

Source: https://habr.com/ru/post/1692352/


All Articles