我收到以下错误,抱怨Collections.sort();
行:
线程“主”中的异常java.lang.Error:未解决的编译问题: 类型Collections中的sort(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());
}
}
答案 0 :(得分:1)
使用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);
答案 1 :(得分:0)
Collections类型的sort(List)方法不适用于参数()
该错误告诉您需要将List
参数传递给Collections.sort()
,但是您没有传递任何参数。