Reputation: 198
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.)
Upvotes: 0
Views: 128
Reputation: 106460
I'm getting frustrated with institutions that shoehorn their curriculum into ridiculous and entirely unrealistic constraints.
In practice, you are going to be using a Comparator<String>
which allows you the flexibility to use lambdas to sort the results. It's also incredibly terse, too.
On principle, what you've described is the only other logical approach. The only way you could practically solve this is to create your own class that encapsulates the String
instance that you want, and sort that.
Upvotes: 4
Reputation: 77206
It sounds like your wrapper object is the simplest way to meet the silly requirement. Just write a method that compares the lengths of the contained strings.
Upvotes: 1