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;
}
3
  • You could just use return project1.getEndTime() - project2.getEndTime() ... but what's the question? Commented Oct 30, 2015 at 4:54
  • This might be helpful Commented Oct 30, 2015 at 4: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. Commented Oct 30, 2015 at 4:59

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.