Programming Create a class called StringLengthComparator and

Programming...

Create a class called StringLengthComparator and make it implement the Comparator Interface (see Special Topic 14.5) for Strings. This interface will require you to create a method called compare() that compares two strings. Your implementation of this method should sort strings by increasing length, and so that strings of the same length are sorted alphabetically. (No main is required for this question; the output below comes from us testing the method from another class.)

Solution

import java.util.Comparator;


public class StringLengthComparator implements Comparator<String>{

   // compare methods needs to be overridden by the class
   @Override
   public int compare(String s1, String s2) {
       //if the s1 length is less than s2 then it should come before s2, hence returning negative number -1
       if(s1.length()<s2.length()){
           return -1;
       }
       //if the s1 length is greater than s2 then it should come after s2, hence returning positive number -1
       else if(s1.length()>s2.length()){
           return 1;
       }
       //if the s1 length is equal than s2 we should compare based on the alphabetical order
       else{
           //compareTo method Compares two strings lexicographically.
           return s1.compareTo(s2);
       }
   }

}

//Note no main method is written as it was clearly mentioned not to do so in the question

If you have any doubt please feel free top ask questions. Thanks a lot. God bless you!

Programming... Create a class called StringLengthComparator and make it implement the Comparator Interface (see Special Topic 14.5) for Strings. This interface

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site