【问题标题】:Java error :- "no suitable method found for sort(Student[],j)"Java 错误:-“找不到适合排序的方法(学生 [],j)”
【发布时间】:2020-06-02 09:43:11
【问题描述】:

大家好,我是 Java 编程新手,在练习时遇到了一个错误,请帮助我解决我上面提到的这个问题(标题)。我也在此处附上我的代码,请解决此问题并提前感谢:)

代码:

import java.util.Collections;
import java.util.Comparator;
class Student{
    public int marks;
    public String name;
    public Student(int marks, String name){
        this.marks = marks;
        this.name = name;
    }
    @Override
    public String toString(){
        return ("Name: " + this.name + " Marks: " + this.marks);
    }
}
public class j implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2){
        if (o1.marks < o2.marks)
            return 1;
        else
            return -1;
    }
    public static void main(String[] args) {
        Student[] array = new Student[2];
        array[0] = new Student(10, "varun");
        array[1] = new Student(20, "gupta");
        Collections.sort(array, new j());
        for (Student i : array)
            System.out.println(i);
    }
}

【问题讨论】:

  • 使用Arrays.sort。此外,您的比较器不具有传递性:compare(s, s) 返回-1(将学生与他们自己进行比较)。
  • Collections.sort 用于对Lists 进行排序。 array 不是 List - 而是顾名思义的数组。
  • 你能提供我的代码(更新的)对我来说非常有帮助和容易学习

标签: java sorting comparator


【解决方案1】:

你应该改变 Collections.sort(array, new j()); to Arrays.sort(array, new j());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    相关资源
    最近更新 更多