0

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 Comparableand 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.)

Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38
jsabina
  • 188
  • 14
  • 1
    Curious. Why couldn't you use a comparator? – DeeV Mar 16 '16 at 21:03
  • university assignment unfortunately :/ I don't understand it either! All the example I could find where with comparator – jsabina Mar 16 '16 at 21:04
  • 1
    That would be because a comparator is the easier way, but it sounds like the professor wants you to understand how overriding and interfaces works or something. – DeeV Mar 16 '16 at 21:05
  • 2
    There are many easier ways, but it sounds like your professor won't let you use any of them. Given the constraints of this assignment, I think what you've done is quite reasonable. – azurefrog Mar 16 '16 at 21:06
  • yeah :( so I guess the only way to implement Comparable is to create my class right? even if I am just using Strings? – jsabina Mar 16 '16 at 21:06
  • 1
    Yes, `String` is final, so you can't subclass it; you *have* to create your own wrapper class. – azurefrog Mar 16 '16 at 21:06

2 Answers2

4

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.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • I agree actually they just create confusion in the mind of people that are just starting to learn!!! Thanks a lot for the answers guys – jsabina Mar 16 '16 at 21:23
1

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.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152