Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of non-comparable elements

Today I was asked this interview question:

If I have a Person class with name, age and salary fields, and I put 100 new instances of this Person in an ArrayList, and then do Collections.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?

like image 460
Victor Avatar asked Jul 02 '13 17:07

Victor


1 Answers

It wouldn't compile: the 1-argument version of Collections.sort expects a list of Comparables. Specifically, a List<T> where T implements Comparable<? super T>.

like image 156
arshajii Avatar answered Oct 11 '22 20:10

arshajii