For a Java assignment I have to sort by length an ArrayList<String>
using the Comparable
interface.
What I have done, and it works, is to create a custom object in a class that implements Comparable
and set the CompareTo()
to use length.
It's ok and it works.
I was just wondering if there is an easier way.
I know that String
in Java already implements Comparable
interface.
But the natural order is lexicographic or alphabetic, not by length.
I have no idea how I can implement a different CompareTo()
for instances of the class String
without having to create my object.
Is there a way?
Or am I missing the logic?
(I cannot use Comparator
, I have to use the Comparable
interface.)