Search code examples
javacomparable

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?


Solution

  • 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>.