Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Comparator compare two objects of different type?

I have two objects of classes Person and Employee. Both classes have common attribute age. And I have added few objects of both theses classes to an Arraylist and now I want two write one Comparator and pass it to sort method of Collections class. And want the list to be sorted on the basis of age. I am trying this just for getting more clarity on use of Comparable and Comparator in Java.

EDIT: Reason Why I was asking this question was that I was not clear about Comparator and Comparable. I read somewhere that If Class implements Comparable then it can not be compared against objects of other classes (Because of Class cast exception).

Now if I create relation ship in Employee and Person then there is no need to implement Comparator (Unless I want to do sorting on the basis of name or other common attribute of these classes).

Once Again, I have asked this question to get more clarity on Comparator and Comparable.

Till now, What I have been able to understand is that If I want to do sorting on more than one parameters then I should implement Comparator and pass it to Collections.srot().

Or If I don't have control over the Class of object being sorted, then custom sorting I should implement Comparator. (Correct me if I am wrong or I am missing something)

EDIT

I think now I understand the use of Comparable and Comparator. To make sure I got the right concepts, here is what I understand: If I want to compare two objects of different classes (and having no relation ) then I should use raw comparator and override the compare method. Another reason why somebody would implement Comparator instead of Comparable is to have flexibility in sorting. And what I understand from natural sorting is the logic implemented by Class in CompareTo method.

Hope I am correct with all these points.

like image 351
AKS Avatar asked Sep 13 '12 20:09

AKS


Video Answer


2 Answers

You can define an interface called Ageable and Employee and Person can implement this interface. Also you can define an abstract class (and Employee and Person will be inherited from the abstract class) with the same effect. Note that you can also use a normal class for this reason, you can do whatever you need.

Also, if there is no reason to say that an Employee is not a Person (for instance robots are working at the office) then Employee can be inherited from Person.

like image 123
Lajos Arpad Avatar answered Sep 30 '22 01:09

Lajos Arpad


I would make an Employee a sub-class of Person. (Assuming all your employees are people) Then you can create a Comparator<Person>

like image 41
Peter Lawrey Avatar answered Sep 30 '22 03:09

Peter Lawrey