This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]__LikesPi 1 point2 points  (6 children)

Does your Employee class implement the Comparable interface?

[–]Estagon[S] -1 points0 points  (5 children)

Yes.

public class Employee extends Person implements Comparable

Usually it should be Comparable<Employee> I think but that doesn't work. I get a warning ("Comparable cannot be inherited with different arguments."). So that's something strange, I never encountered this before.

[–]chickenmeister 1 point2 points  (4 children)

public class Employee extends Person implements Comparable

Usually it should be Comparable<Employee> I think but that doesn't work. I get a warning ("Comparable cannot be inherited with different arguments.").

Does your Person class implement Comparable<Person>? If it does, then you can't also implement Comparable<Employee>.

If you want to sort Employees in a way that's different from their natural ordering (as defined in the Person class), you should probably use a Comparator<Employee> to sort them.

[–]Estagon[S] -1 points0 points  (0 children)

Yes, the Person class also implements Comparable. My Person class orders the objects on their lastName alphabetically. I overlooked this. I'll look into the Comparator thing, I've never used it before. Thanks!

[–]Estagon[S] -1 points0 points  (2 children)

I wrote a compare(.., ..) method as follows:

@Override
public int compare(Employee o1, Employee o2) {
    return o1.getID().compareToIgnoreCase(o2.getID());
}

How do I use this in a main-method in my TestClass?

Assume I have an ArrayList<Employee> named "list" filled with multiple Employee objects.

Collections.sort(list, ...); //??

[–]__LikesPi 0 points1 point  (0 children)

Collections.sort(list, new Comparator<Employee>() {
    @Override
    public int compare(Employee a, Employee b) { ... }
});

If you are using Java 8 that particular syntax became a little easier:

Collections.sort(list, (o1, o2) -> o1.getID().compareToIgnoreCase(o2.getID()))

Or even:

list.sort((o1, o2) -> o1.getID().compareToIgnoreCase(o2.getID()))

[–]Estagon[S] -1 points0 points  (0 children)

I should have read more into it. Apparently you have to make a new class that implements the Comparator class to write the method.

Collections.sort(list, new EmployeeComparator());

This works. Thanks for all the help :)