Comparable interface lies in java.lang package. It is used to sort object in their natural order, i.e. number by numeric order, text in lexical order, dates in chronological order.

Similarly, when you define your own objects, e.g. Person, sorting it on name sounds natural.

Comparable interface defines abstract method compareTo(), you need to override this method to implement the natural order sorting of objects in Java.

Decision can be taken based on below returned value:

  • +VE = If the object, on which you are calling this method is greater than another object.
  • -VE = If the object, on which you are calling this method is less than another object.
  • 0 VE = If both objects are equal.

You need to call compareTo() method if you are comparing objects. Prefer relational operator over arithmetic operator for comparing numeric fields for better performance.

Example of Comparable:

Output:

List of unsorted languages:[Java, C, C++, Python, PHP] List of sorted languages:[C, C++, Java, PHP, Python]

Point to remember : Prefer to use numeric and keep consistent with compareTo() method. Integer numbers should not extend the maximum value of integer in Java.

It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *