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
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)
Comparable objects using their natural ordering void sort(List list, Comparator super T> c)
ComparatorYou'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:
Comparable (use the 1-arg sort)Comparator for the type must be provided (use the 2-args sort)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.