【问题标题】:Error when using Collections.sort() [duplicate]使用 Collections.sort() 时出错 [重复]
【发布时间】:2015-07-01 21:50:08
【问题描述】:

我想知道为什么在尝试对列表进行排序后出现错误。 当我尝试对包含“学生”对象的列表进行排序时发生错误。

import java.lang.reflect.Array;
import java.util.*;
import java.util.ArrayList;

public class mainProgram {
    public static void main(String[] args) {
        List<Student> classStudents = new ArrayList<Student>();

    //Add 4 students to List
        classStudents.add(new Student("Charles", 22));
        classStudents.add(new Student("Chris", 25));
        classStudents.add(new Student("Robert", 23));
        classStudents.add(new Student("Adam", 21));

    //sort and print
        Collections.sort(classStudents);    //Why does this not work?
        System.out.println("classStudent(Sorted) ---> "
        + Arrays.toString(classStudents.toArray()));
    }
}

class Student implements Comparable<Student>{
    // fields
    private String name;
    private int age;

    //Constructor
    public Student(String name, int age){ 
        name = name;
        age = age;
        }
    //Override compare
    public int CompareTo(Student otherStudent){
        if(this.age == otherStudent.age){
            return 0;
        } else if(this.age < otherStudent.temp){
            return -1;
        } else{
            return 1;
        }
    }

    //Override toString
    public String toString(){
        return this.name + " " + this.age;
    }
}

interface Comparable<Student>{
    int CompareTo(Student otherStudent); 
    String toString();
}

错误是:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<Student>). The inferred type Student is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

我不明白错误的含义以及如何修复它。非常感谢您的意见。

【问题讨论】:

    标签: java sorting comparator comparable


    【解决方案1】:

    根据错误消息可能不是那么明显,但是如果您查看documentation of Collection.sort,您会发现此方法(与其他标准 API 方法一样)需要实现的实例列表已经在 API 中定义接口 在这种情况下是java.lang.Comparable

    所以不要尝试创建自己的Comparable 接口。请记住,如果某个方法需要某种类型,则该类型必须已经在某处定义(否则具有这种方法的类将无法编译,因为方法不能使用某些未知/未定义的类型)。

    java.util.Comparable 中定义的比较方法也是compareTo 而不是CompareTo(Java 区分大小写,因此这些方法不被视为相等)。


    其他问题是

    • Student 没有 temp 字段所以

      } else if (this.age < otherStudent.temp) {
      

      应该是

      } else if (this.age < otherStudent.age) {
      

      甚至更好,而不是这个age比较条件if(..&lt;..){-1} else if(..==..){0} else {1}只需使用

      return Integer.compare(age, otherStudent.age);
      
    • 在构造函数中,您需要this.name 来确定您指的是哪个namethis.name 表示此实例的字段,name 是对传递给构造函数的变量的引用。所以你需要

      public Student(String name, int age) {
          this.name = name;
          this.age = age;
      }
      

    【讨论】:

      【解决方案2】:

      做了些小改动,看看:

      MainProgram.java

          import java.util.ArrayList;
          import java.util.Arrays;
          import java.util.Collections;
          import java.util.List;
      
          public class MainProgram {
      
              public static void main(String[] args) {
                  System.out.println("HI !!!");
                  List<Student> classStudents = new ArrayList<Student>();
      
              //Add 4 students to List
                  classStudents.add(new Student("Charles", 22));
                  classStudents.add(new Student("Chris", 25));
                  classStudents.add(new Student("Robert", 23));
                  classStudents.add(new Student("Adam", 21));
      
              //sort and print
                  Collections.sort(classStudents);    //Why does this not work?
                  System.out.println("classStudent(Sorted) ---> "
                  + Arrays.toString(classStudents.toArray()));
              }
          }
      

      Student.java

      class Student implements java.lang.Comparable<Student>{
          // fields
          private String name;
          private int age;
      
          //Constructor
          public Student(String name, int age){ 
              this.name = name;
              this.age = age;
              }
      
          //Override compare
          public int compareTo(Student otherStudent){
              if(this.age == otherStudent.age){
                  return 0;
              } else if(this.age < otherStudent.age){
                  return -1;
              } else{
                  return 1;
              }
          }
      
          //Override toString
          public String toString(){
              return this.name + " " + this.age;
          }
      }
      

      输出: classStudent(Sorted) ---> [Adam 21, Charles 22, Robert 23, Chris 25]

      【讨论】:

        【解决方案3】:

        Java 定义了自己的 Comparable 接口。删除你的并导入那里, collections 方法使用 java 的。

        【讨论】:

          【解决方案4】:

          如果你要对它进行排序,你的Student 类需要实现java.lang.Comparable 接口。否则,该方法怎么可能知道排序的标准?

          这应该会有所帮助:Why should a Java class implement comparable?

          【讨论】:

            【解决方案5】:

            首先,您重写了 Comparable 接口方法“compareTo()”,这是一个错字——它应该是小写的“c”,而不是大写。

            其次,我不知道您要对开头的最后一点“interface Comparable”做什么。删除那部分 --- 你不需要它。

            Comparable 接口是 API 的一部分。

            干杯。

            【讨论】:

              猜你喜欢
              • 2017-04-17
              • 2020-09-22
              • 2020-01-16
              • 1970-01-01
              • 1970-01-01
              • 2018-05-13
              • 2018-11-28
              • 2016-09-12
              • 1970-01-01
              相关资源
              最近更新 更多