4

I'm trying to write a sort method in an interface that extends Iterable<T> but it doesn't work, I think that it is "logically" correct but it doesn't swap the elements. The interface is used to create a List very similar to the one in Java and my goal is to create a class inspired to the LinkedList so it has the ListIterator. Any suggestions? Here's the code of the method:

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();
    }
}

1 Answers1

1

You can use Collections.sort in order to sort efficiently 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);
    }
}
Yassine Badache
  • 1,810
  • 1
  • 19
  • 38
  • That will never work since I don't actually have the list in the interface and I can only use the iterator there – Andreascopp Jan 18 '18 at 10:46