Today I was asked this interview question:
If I have a
Person
class withname
,age
andsalary
fields, and I put 100 new instances of thisPerson
in anArrayList
, and then doCollections.sort(list)
, then on what parameter will the list be sorted?
I understand that I need to have the Person
class implement Comparable
and then override compareTo
, but if I don't do that, what will happen?
as the Collections API states:
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
If the
Person
class does not implementComparable<Person>
, then (as the compiler will inform you):(If you happened to have a
Comparator<Person>
lying around,Collections.sort(myList, myComparator)
would sort it by the ordering specified by the comparator.)It wouldn't compile: the 1-argument version of
Collections.sort
expects a list ofComparable
s. Specifically, aList<T>
whereT
implementsComparable<? super T>
.Yes you can sort a collection without making the elements implement the Comparable Interface, you do this
/edit,
if you use Collections.sort(List) then it will compile only if the list is generic and it's elements implements Comparable. And if so, then the implementation of the compareTo(Obj) on each element is what will determine the ordering in the list after the sort(List) method is called