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?
                        
Either you use a structure which uses the
Comparableinterface to order its elements when you add a new element inside it :Either you use a
Listand theCollections.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):With the
TreeSet, the elements are sorted as soon as added and with theList, the elements are not sorted when you add them.Only, the call to the
Collections.sort()method sorts the list.