简体   繁体   中英

String and Comparable Interface

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM