How to use Comparator in Java to sort

后端 未结 14 2059
时光取名叫无心
时光取名叫无心 2020-11-22 02:19

I learned how to use the comparable but I\'m having difficulty with the Comparator. I am having a error in my code:

Exception in thread \"main\" java.lang.C         


        
14条回答
  •  情书的邮戳
    2020-11-22 02:54

    Use People implements Comparable instead; this defines the natural ordering for People.

    A Comparator can also be defined in addition, but People implements Comparator is not the right way of doing things.

    The two overloads for Collections.sort are different:

    • > void sort(List list)
      • Sorts Comparable objects using their natural ordering
    • void sort(List list, Comparator c)
      • Sorts whatever using a compatible Comparator

    You're confusing the two by trying to sort a Comparator (which is again why it doesn't make sense that Person implements Comparator). Again, to use Collections.sort, you need one of these to be true:

    • The type must be Comparable (use the 1-arg sort)
    • A Comparator for the type must be provided (use the 2-args sort)

    Related questions

    • When to use Comparable vs Comparator
    • Sorting an ArrayList of Contacts

    Also, do not use raw types in new code. Raw types are unsafe, and it's provided only for compatibility.

    That is, instead of this:

    ArrayList peps = new ArrayList(); // BAD!!! No generic safety!
    

    you should've used the typesafe generic declaration like this:

    List peps = new ArrayList(); // GOOD!!!
    

    You will then find that your code doesn't even compile!! That would be a good thing, because there IS something wrong with the code (Person does not implements Comparable), but because you used raw type, the compiler didn't check for this, and instead you get a ClassCastException at run-time!!!

    This should convince you to always use typesafe generic types in new code. Always.

    See also

    • What is a raw type and why shouldn't we use it?

提交回复
热议问题