java - 如何解决我的代码中的集合排序?
问题描述
我收到以下抱怨该Collections.sort();
行的错误:
线程“main”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());
}
}
解决方案
使用 aList
而不是 a 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);
推荐阅读
- powerbi - DAX PowerBI - 基于数据类型的动态测量
- cmake - 如何在 cmake 中为 OpenCV 启用 GTK+?
- jquery - 修复对完整日历获取资源的多次请求
- python - 如何在不丢失格式的情况下在新电子邮件中发送现有消息
- python - 将值从一个 Tkinter 帧保存到另一个
- c++ - 如何在自己的班级中重载“+”和“<<”运算符
- javascript - 单击其中的组件时触发 onClick 处理程序
- chart.js - 如何制作多个堆叠图表以共享相同的 yAxis?
- python - 附加数组时 Numpy 返回错误的问题
- javascript - 过滤JS数组