Search code examples
javasortingcollectionscomparatorcomparable

Creating a comparator to pass to .sort() in java not suitable method error


I am fairly new to programming. I am doing this assignment and I cannot figure out why I am getting "no suitable method for sort" error. This is the call to sort from DirectorySortDemo:

public class DirectorySortDemo{
  public static void main(String[] args){
    String dirNames = {"dir12", "dir1", "dir11", "dir10", "dir2"};
    ArrayList<String> directories = new ArrayList<>(Arrays.asList(dirNames));
    Collections.sort(directories, new DirectoryComparator());
    }
}

This is the comparator:

public class DirectoryComparator implements Comparable<String> {
   @Override
   public int compareTo(String o) {
     return -1;
   }
}

I have tried, instead of writing "String" after Comparable, typing "DirectoryComparator", but it did not work. What am I doing wrong? The overall goal is to compare the elements of the array list and make it so the elements with two digits are greater than the elements with one digit. I think the return -1 statement does not make a difference. Although, I tried coding a solution, and the error still remains.


Solution

  • Collections.sort accepts a Comparator<T> as the second argument, you are giving it a Comparable<T>. This is why the error pops up.

    Even if Collections.sort did accept a Comparable<T>, your implementation violates the general contract of Comparable.

    You seem to just want to sort the strings in reverse order. You can just do something like this:

    Collections.sort(directories, Comparator.reverseOrder());
    

    If I misunderstood you and you actually want to sort it in some custom way, you can do something like this:

    Collections.sort(directories, Comparator.comparing(s -> /*map the string to something you want to compare*/));