Java中自定义对象的排序数组 [英] Sorting Array of Custom Object in Java

查看:114
本文介绍了Java中自定义对象的排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将项目结束时间从最小到最大排序。

I am trying to sort the Project end times from smallest to largest values.

我创建了一个名为Project的自定义对象列表,并尝试根据由访问器返回的值。我已经重载了compare函数并收到错误:

I have created a list of custom objects called Project and am attempting to sort them based on a value returned by an accessor. I have overloaded the compare function and am receiving the error:


Collections类型中的sort(List,Comparator)方法不适用于参数(Project [],new Comparator(){})

The method sort(List, Comparator) in the type Collections is not applicable for the arguments (Project[], new Comparator(){})

下面显示了我主要代码,所有帮助

The code from my main is shown below, any and all help appreciated.

Collections.sort(projectList, new Comparator< Project>(){

    @Override
    public int compare(Project project1, Project project2)
    {   
       return compareProjects(project1, project2);}
    }
);

public static int compareProjects(Project project1, Project project2)
{ 
    if (project1.getEndTime() > project2.getEndTime())
        return 1;
    else
        return 0;
}

和我的项目类别:

public Project(int projectNum, int start, int end)
{
    this.projectNum = projectNum;
    this.start = start;
    this.end = end;
    this.length = end - start;
}

public static int getEndTime()
{
    return end;
}


推荐答案


Collections.sort对列表进行操作,而Arrays.sort对数组进行操作

需要更改 Project.class ,实现 Comparable interface

class Project implements Comparable<Project> {

    @Override
    public int compareTo(Project o) {
        if (this.getEndTime() > o.getEndTime())
        return 1;
    else
        return 0;
    }
}

然后在您的 main中。 class

Arrays.sort(projectList);

这篇关于Java中自定义对象的排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆