Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

java - sorting string lengths using comparator

While trying to sort an array based on its element string lengths, I am struck with a compile error. I have an set to start with, ,

Set<String> arraycat = new HashSet<String>();
//add contents to arraycat
String[] array = arraycat.toArray(new String[0]);
//array looks like this now:
//array=[cat,cataaaa,cataa,cata,cataaa]

I would ideally want to sorted to

array=[cat,cata,cataa,cataaa,cataaaa]

so I have a comparator of type

class comp implements Comparator {

    public int compare(String o1, String o2) {
        if (o1.length() > o2.length()) {
            return 1;
        } else if (o1.length() < o2.length()) {
            return -1;
        } else {
            return 0;
        }
    }
}

and then I call the class by

Collections.sort(array, new comp());

but then, it throws me two compile errors:

comp is not abstract and does not override abstract method   compare(java.lang.Object,java.lang.Object) in java.util.Comparator
class comp implements Comparator {
^
testa.java:59: cannot find symbol
symbol  : method sort(java.lang.String[],comp)
location: class java.util.Collections
Collections.sort(array, new comp());
^2 errors

I would appreciate any clues to solve the problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to specify a type parameter for Comparator for your implementation to work.

class comp implements Comparator<String> {
  public int compare(String o1, String o2) {
    if (o1.length() > o2.length()) {
      return 1;
    } else if (o1.length() < o2.length()) {
      return -1;
    } else {
      return 0;
    }
  }
}

In Java 1.7 and later, you can also simplify the body of this method to:

class comp implements Comparator<String> {
  public int compare(String o1, String o2) {
    return Integer.compare(o1.length(), o2.length());
  }
}

Also, Collections.sort sorts List objects. Since you're sorting an array, you should use Arrays.sort:

Arrays.sort(array, new comp());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...