Sorting Array of Custom Object in Java

倾然丶 夕夏残阳落幕 提交于 2019-12-25 14:33:27

问题


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

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:

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;
}

and my Project Class:

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;
}

回答1:


Collections.sort operates on a List, and Arrays.sort operates on an array

Need to changes Project.class , implement Comparable interface

class Project implements Comparable<Project> {

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

Then in your main.class

Arrays.sort(projectList);



回答2:


You never return -1 (e.g <). However, I would suggest you use Integer.compareTo(int, int) which returns the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y like

public static int compareProjects(Project project1, Project project2) {
    return Integer.compare(project1.getEndTime(), project2.getEndTime());
}

Also, since projectList is an array of Project you can get it as a List<Project> with Arrays.asList(T...) like

Collections.sort(Arrays.asList(projectList),


来源:https://stackoverflow.com/questions/33428901/sorting-array-of-custom-object-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!