How would I go about sorting an array of objects based on a specified property. For instance, if I had an array of movie objects called Movie movies, and the movie class had the properties String title, int popularity, and Date releaseDate, how would I go about writing methods that sort the array based on either title, popularity, or releaseDate?
For instance, I have this class which compares the releaseDate of two rentals:
I also have a compareTo method in the Rentals class (which is the superclass for Movies and implements Comparable) which compares two strings(titles).
How do I implement Arrays.sort for these two types of comparison methods?
Well, if I'm not mistaken, the DateComparison class will work perfectly fine for Movie as well, since Movie is a subclass of Rental. You can just call the Arrays.sort() method with the Movie array, and the DateComparison Comparator.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Joined: Nov 28, 2011
So would I write it likes this:
And then how would I call Arrays.sort for my compareTo and compare methods?
Kd Martin wrote:How do I call them in the Arrays.sort. Is it Arrays.sort(movies, compare())? I'm having trouble understanding how to call these methods as a parameter in the Arrays.sort
"kd", please read the last two replies by Stephan and Jeff. They provide the complete answer. While reading them you should be aware that you are making some incorrect assumptions about the process, so be prepared to recognize them as you read.
Arrays.sort will use the compareTo method of its elements if you don't provide a Comparator. If you do, it will use the compare method of the comparator. That's how it works. To be able to sort on another field you just create a new Comparator.
Kd Martin wrote:These methods which are in my Rental class.
Yes, you already told us that.
How do I call them in the Arrays.sort. Is it Arrays.sort(movies, compare())? I'm having trouble understanding how to call these methods as a parameter in the Arrays.sort
That question was just answered a few posts ago. Simply re-asking the same question won't get you anywhere. If you didn't understand the answers, ask for clarification. Make sure to be as specific as possible about what parts of the answers you didn't understand.