3

I have -

import java.util.*;

public class TestCompare {

    List<String> list = Arrays.asList("10", "1", "20", "11", "21", "12");
    Comparator<String> cmp = new Comparator<String>() {
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
        }
    };
    Collections.sort(list, cmp);
}

At Collections.sort(list, cmp); there is an error - Syntax error on token "(", delete this token. What is wrong in this syntax ?

4 Answers 4

10

You can't have code directly in a class, it should be in a method like main:

public class TestCompare {
    public static void main() {
      List<String> list = Arrays.asList("10", "1", "20", "11", "21", "12");
      Comparator<String> cmp = new Comparator<String>() {
      public int compare(String o1, String o2) {
        return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
      }
      };
      Collections.sort(list, cmp);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

How can I run by eclispe this class when the main is an inner function ?
@URL87 Just use the run... wizard
it will crash when the source array contains non-numeric value
9

You need to wrap your code in a method, not directly in the class block.

Comments

0

At class level, only declarations (and initializer) blocks are allowed. Your first two statements are declarations (they are interpreted as field declarations, even though that is probably not your intention). The third is not a declaration, so it fails.

Declarations can be: methods, fields, constructors, inner classes

Comments

0

Post 1.8 you can use lambda expression too.

public class TestCompare {
    public static void main() {
      List<String> list = Arrays.asList("10", "1", "20", "11", "21", "12");
        Comparator<String> cmp = (o1, o2) -> {
            return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
        };
        Collections.sort(list, cmp);
     }
}

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.