如何解析代码中的集合排序



我收到以下关于Collections.sort();行的错误:

线程"main"java.lang中出现异常。错误:未解决的编译问题:Collections类型中的方法排序(List(不适用于参数((

这是我的代码:

import java.util.*;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author apuga
*/
public class Modules implements Comparator<Modules> {
public String getName() {
return name;
}
public String getMarks() {
return marks;
}
private String name;
private String marks;
Queue allModules = new LinkedList<>();
Scanner input = new Scanner(System.in);
public Modules(String name, String marks) {
this.name = name;
this.marks = marks;
}
public Modules() {
}
@Override
public String toString() {
return name + "t" + marks + "t" + "t" + "t" + "t";
}

public void addModule() {

for (int i = 0; i < 4; i++) {
Modules newM = new Modules(name, marks);
if (allModules.size() < 4) {
System.out.println("Enter a module name");
newM.name = input.nextLine();
System.out.println("name = " + newM.name);
System.out.println("Enter marks");
newM.marks = input.nextLine();
System.out.println("marks = " + newM.marks);
allModules.add(newM);

} else {
System.out.println("Adding a module will delete the first module name and marks");
System.out.println("Enter a module name");
newM.name = input.nextLine();
System.out.println("name = " + newM.name);
System.out.println("Enter marks");
newM.marks = input.nextLine();
System.out.println("marks = " + newM.marks);
allModules.add(newM);
allModules.remove();
}
}
System.out.println("Unsorted : "+allModules);
Collections.sort();// <---- here is where i need help .

}

public static void main(String args[]) {
Modules newmodule = new Modules();
newmodule.addModule();
}
@Override
public int compare(Modules o1, Modules o2) {
return o1.getMarks().compareTo(o2.getMarks());
}
}

使用List而不是Queue(因为它是Collections.sort(List, Comparator)(。不要使用原始类型!

List<Modules> allModules = new LinkedList<>();

然后更改

allModules.remove();

allModules.remove(0);

最后,调用Collections.sort并像一样显示结果

System.out.println("Unsorted : " + allModules);
Collections.sort(allModules, Comparator.comparing(Modules::getMarks));
System.out.println("Sorted : " + allModules);

Collections类型中的方法sort(List(不适用于arguments((

错误告诉您需要将List参数传递给Collections.sort(),但您没有传递任何参数。

最新更新