Use People implements Comparable<People>
instead; this defines the natural ordering for People
.
A Comparator<People>
can also be defined in addition, but People implements Comparator<People>
is not the right way of doing things.
The two overloads for Collections.sort
are different:
<T extends Comparable<? super T>> void sort(List<T> list)
Comparable
objects using their natural ordering<T> void sort(List<T> list, Comparator<? super T> c)
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<Person>
). 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<People> peps = new ArrayList<People>(); // 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<Person>
), 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.