地址簿比较器</identifier>的<identifier>预期错误

时间:2015-04-15 19:32:48

标签: java linked-list comparator

这里似乎有什么问题?

public class ABook {
  public static void main(String args[]) {
      LinkedList addressBook = new LinkedList(); //creates linked list
      Scanner input = new Scanner(System.in);
      int n = 1; //this will be used for the loop to act as a counter for the loop
      do {
        System.out.println("Would you like to add a friend? (Say Y or N)");
        String reply = input.nextLine();
        if (reply.equals("Y")) {
          System.out.println("What is the name of your friend?");
          String name = input.nextLine();
          System.out.println("What is the age of your friend?");
          int age = input.nextInt();
          Friend newFriend = new Friend(name, age);
          addressBook.add("Name: " + newFriend.name + "; " + "Age: " + newFriend.age);
          Comparator < CustomObject > comparator = new Comparator < CustomObject > () {
            public int compare(CustomObject c1, CustomObject c2) {
              return c2.getAge() - c1.getAge(); // use your logic
            }
            Collections.sort(addressBook, comparator);
            System.out.println("This is your Address Book so far: " + addressBook);
            n++;
          }
        }
    ...
}

编译器在这里抱怨:

Collections.sort(addressBook, comparator);

<identifier> expected错误。

如果您能找到解决方案,您能解释一下解决方案的工作原理和原因,以及比较器的含义。

1 个答案:

答案 0 :(得分:1)

Collections.sort的调用在方法compare之外,但在匿名内部类的定义内。

完成匿名类和Collections.sort变量的声明后,将调用移至comparator

您还需要在结束匿名类声明的}之后添加分号。