13

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.

6 Answers 6

17

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());
Sign up to request clarification or add additional context in comments.

7 Comments

Hi Lawrence.. thanks for this.. That has solved the first compile error: but, Ive still got another compile error saying: "cannot find symbol symbol : method sort(java.lang.String[],comp) location: class java.util.Collections Collections.sort(array, new comp());" I have imported the util* package, not sure why I am getting this error
sort() takes a List, not a String[] array. Use Arrays.asList() to convert it.
Also, for a simpler comparator, consider using Integer.signum(int) instead of the if/else-if/else; e.g. return Integer.signum(o1.length() - o2.length());
this question is too old but anyway... there is no need to convert the array to list, you can sort it like that: Arrays.sort(array, new comp());
@RobHruska If JDK >= 1.7, one can even use Integer.compare(o1.length(), o2.length()).
|
7

You need to use Arrays.sort() method if data source is an array.

For instance,

String []array={"first","second","third","six"};

Arrays.sort(array,new Comparator<String>()
{
  public int compare(String s1,String s2)
   {
    return s1.length() - s2.length();
    }
});

Or convert array to List to use Collections.sort() method,

Collections.sort(Arrays.asList(array),new Comparator<String>()
{
  public int compare(String s1,String s2)
   {
    return s1.length() - s2.length();
    }
});

Comments

6

One Liners

Ascending

Arrays.sort(words, Comparator.comparingInt(String::length));

Descending

Arrays.sort(words, Comparator.comparingInt(String::length).reversed());

Comments

2

Should be

class comp implements Comparator<String> { ...

or even better

Collections.sort(array, new Comparator<String> { ...

(and not even name the class that's only used once)

1 Comment

You need to specify the type-variable! Comparator <String>
1

Achieved same by using stream and comparator as below-

Arrays.stream(array)
      .sorted(Comparator.comparingInt(String::length))
      .forEach(a -> System.out.print(a + " "));

Comments

0

I had a similar assignment recently and I'll provide you with an additional example.

import java.util.Arrays;
import java.util.Comparator;
//for more information: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

/**
 *
 * @author Xilef
 */
public class StringKorter implements Comparator<String> {
    @Override
    public int compare(String s1, String s2){
        if (s1.length() > s2.length())
         return 1;
        else if (s1.length() < s2.length())
         return -1;
        else return 0;
    }
    public static void main(String[] args) {
        String[] woorden = { "boot", "kinderen", "stoel", "volwassenen", "ei", "stoel", "kop", "zeshoek", "stoel", "ei" };
        System.out.println("woorden: " + Arrays.toString(woorden));//before sorting by length
        Arrays.sort(woorden, new StringKorter());
        System.out.println("Array woorden after sorting by length: " + Arrays.toString(woorden));
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.