Search code examples
javainheritancearraylistcomparable

Java Sort with Comparable


I have an ArrayList of Person objects. A Person has name, age and height. My goal is to sort this ArrayList<Person>. I have implemented Comparable<Person> and have defined compareTo() but when I try to sort it, it give me this error:

The method sort(Comparator) in the type ArrayList is not applicable for the argument ()"

The way I understand is that if you implement Comparable and then define compareTo everything else is magically done for you.

Can some one explain how to this works and why I am getting this error?


Solution

  • Either you use a structure which uses the Comparable interface to order its elements when you add a new element inside it :

    TreeSet<Person> persons = new TreeSet<>();
    Person personOne = ...
    Person personTwo = ...
    persons.add(personOne);
    persons.add(personTwo);
    

    Either you use a List and the Collections.sort(List<T> list) method which takes as argument the list you want to sort (there is an overload of this method but it is not relevant in your case):

    List<Person> persons = new ArrayList<>();
    Person personOne = ...
    Person personTwo = ...
    persons.add(personOne);
    persons.add(personTwo);
    Collections.sort(persons);
    

    With the TreeSet, the elements are sorted as soon as added and with the List, the elements are not sorted when you add them.
    Only, the call to the Collections.sort() method sorts the list.