0

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;
}
Saikat Biswas
  • 114
  • 1
  • 9
sBourne
  • 483
  • 1
  • 5
  • 17
  • You could just use `return project1.getEndTime() - project2.getEndTime()` ... but what's the question? – MadProgrammer Oct 30 '15 at 04:54
  • [This](http://stackoverflow.com/questions/3699141/how-to-sort-an-array-of-ints-using-a-custom-comparator) might be helpful – TheLostMind Oct 30 '15 at 04:54
  • 3
    `is not applicable for the arguments (Project[], new Comparator(){})` I'm pretty sure that your answer right there. `Project[]` is an array, not a list. – markspace Oct 30 '15 at 04:59

2 Answers2

4

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);
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0

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),
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249