Collections.sort() error

前端 未结 2 1402
抹茶落季
抹茶落季 2021-01-27 00:07

I am trying to sort a list of type A named BinOrder in class B according to Class A\'s int r.

However i am receiving this error for the line Collections.sort(BinOrder);<

相关标签:
2条回答
  • 2021-01-27 00:45

    To be able to use the single-argument version of Collection.sort() on an ArrayList of A, A should implement the Comparable interface:

    public class A implements Comparable<A> {
      ...
      @Override
      int compareTo(A rhs) {
        ...
      }
    }
    
    0 讨论(0)
  • 2021-01-27 01:02

    Here's the signature of Collections.sort :

    public static <T extends Comparable<? super T>> void sort(List<T> list)
    

    A must implement Comparable for this method.

    You try to pass BinOrder to this method, when BinOrder is of type ArrayList<A>, but since A does not implement Comparable<A>, it doesn't fit the signature of the method.

    Either change A to implement Comparable, or use the sort method that accepts a Comparator :

    public static <T> void sort(List<T> list, Comparator<? super T> c)
    
    0 讨论(0)
提交回复
热议问题