简体   繁体   中英

Sorting Array of Custom Object in Java

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

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

You never return -1 (eg < ). 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),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM