Create a class called StringLengthComparator and make it imp

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<T> implements Comparator<T>{
   public int compare(T arg0, T arg1) {
       if(arg0.toString().length() == arg0.toString().length()){
           return arg0.toString().compareTo(arg1.toString());
       }
       else return arg0.toString().length() - arg0.toString().length();
   }  
}

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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site