I would like to sort the objects in my arraylist called "theSounds" in descending order by their lengths. I know i have to use Collections.sort(theSounds) but not sure how to get this to word in the compareTo method.
I have looked at the documentation https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html but still cant get my head round this.
Could someone explain how I can go about this please?
Wendy Jackson wrote:yes, thats what I thought initially as well but because I have my arraylist in the SortSounds method, thought I could sort them in descending order from this class?
You will be sorting them in that class.
The sort() method uses the compareTo method of a Comparable to determine the ordering.
Write compareTo on Sounds so it orders "normally", and use the reverseOrder() method to get a reversed comparator.
It is not called CompareTo. Similarly your Sounds class should be called Sound. I also think you should call the field something different.
Wendy Jackson wrote:. . . Comparable . . . method CompareTo . . .
I see you have seen the Java™ Tutorials section (well done looking there first ) and if you cannot work out how to compare by length of words, I think you need to resort to desperate measures. Find a pencil and paper and eraser and turn your computer off. When you can write down how to distinguish the lengths of Strings on paper, then you will find it easy enough to write in code.
Since lengths of words are always positive, the comparisons can be simpler than in some circumstances.
To make the code slightly less verbose, I added the method 'getSoundsLength() to the Sounds class. Here goes: