I have an arraylist of type 'DVD' that I want to sort on a particular object. I think I understand the basics but I am having trouble understanding what I should return and the syntax.
I know the above is wrong but it gives you the idea what I want to compare. What I don't quite understand is how to return the sorted DVD instance rather than the title and of course how to define the class for the Comparator declaration. TIA.
Thanks. I just missed that part of the syntax. As for the returned value it was not clear to me from the documentation and examples what 'compareTo' was really returning. Am I correct that it returns an arraylist index of the instance rather than the instance or object itself?
The API documentation of Comparator.compare() says:
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
What the actual number is doesn't matter. The only thing that matters is that it's < 0, == 0 or > 0.
The compare() method should only compare the two DVD objects that it gets passed as arguments. It doesn't know anything about the list that is being sorted; it doesn't even know that the DVDs are in a list. So it doesn't know anything about arraylist indices.
Thanks. It seems to be working now. I am guessing that the sort uses some kind of sorting algorithm that simply uses the returned value of the comparator to order the list. Thus the number of calls to the comparator can be significant for large lists. Out of curiosity does anyone know the sort algorithm used and its performance for large lists?
Yes, the only job of the Comparator is to compare two objects, and the result will be used for the sorting algorithm. The Comparator doesn't need to know anything about the sorting algorithm - which is good, because it means a different algorithm could be used in a future release and it will still work. It's an example of separation of concerns, an important principle in software engineering.