Pages

Tuesday, March 19, 2013

How recollect Comparable and Comparator..Its made easy


Even though I have used Comparable and Comparator methods on various occations and used it meaningfully still sometimes it was hard to recollect which characterstics belong to which one.

Then slowly I developed a technique to remember it - 

Here is how:

Comparabl'e' Comparato'r'
I remember ending e......and ending r

When I face 'e' - I see its one argument
When I face 'r' - I see its multiple argument

With above half of my problem is solved....

Next part is method names:

compareTo - from the name I can figure out that it has compare one object with another (which is passed as argument)

On the other side, compare method, where I have to pass two objects as an argument for making comparison between them.

Putting together

ComparableOne ArgumentcompareTo method
ComparatorTwo Argumentscompare method

Both compareTo and compare methods returns integer values. 
-ve if right is greater than left, zero if both are equal and +ve if left is greater than right

How is it now? Simple or??

No comments:

Post a Comment