首页 > 解决方案 > 如何解决我的代码中的集合排序?

问题描述

我收到以下抱怨该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());
    }
}

标签: javasortingcomparator

解决方案


使用 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);

推荐阅读