Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What is difference between comparator and comparable interfaces? when we use comparator when we use comparable?

user-image
Question added by mahamadali jinna shaik
Date Posted: 2014/08/31
Mohd shahnawaz khan
by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution

Comparator :Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc.

2.Class whose objects to be sorted do not need to implement this interface.Some other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id

3.int compare(Object o1,Object o2)

This method compares o1 and o2 objects. and returns a integer.Its value has following meaning.1. positive – o1 is greater than o22. zero – o1 equals to o23. negative – o1 is less than o1

4.Collections.sort(List, Comparator)

Here objects will be sorted on the basis of Compare method in Comparator.

5.Present in Java.util.Comparator

Comparable

1.Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects

2.Class whose objects to be sorted must implement this interface.e.g Country class needs to implement comparable to collection of country object by id.

3.int compareTo(Object o1)

This method compares this object with o1 object and returns a integer.Its value has following meaning1. positive – this object is greater than o12. zero – this object equals to o13. negative – this object is less than o1

4.Collections.sort(List)

Here objects will be sorted on the basis of CompareTo method

5. Present in Java.lang.Comparable

 

 

java.lang.Comparable: If a class implements comparable it will define natural sorting of that object. if it is a number /sting, sorting follows ascending to descending order. 

This method compares this object with o1 object and returns a integer.Its value has following meaning1. positive – this object is greater than o12. zero – this object equals to o13. negative – this object is less than o1

e.g java.util.Date uses this interface to return after, before dates.

 

java.util.Comparator: Custom sorting mechanism.It compares two objects based on constraint. e.g if a person object has name, age attributes and fetch details based on age order of all persons. then this is best way to follow.

This method compares o1 and o2 objects. and returns a integer.Its value has following meaning.1. positive – o1 is greater than o22. zero – o1 equals to o23. negative – o1 is less than o1

Based on sorting mechanism developer can prefer which is opted.

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.