Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Help Java C Comparable Interface

Related Tutorials


 
 

Share on Google+Share on Google+

Comparable Interface

Advertisement
While writing the object-oriented programs, comparison of two instances of the same class is often required.

Comparable Interface

     

While writing the object-oriented programs, comparison of two instances of the same class is often required. Once instances are comparable, we can sort them in any order. Comparable interface is defined in java.lang package and is used to define the natural sort order of a class. While the interface java.lang.Comparator defines an auxiliary sort order for a class. 

Comparable interface can be implemented by implementing only one method: compareTo. Implement the existing class by defining the the natural order of that class. compareTo() method compares the two object of same type and returns a numerical result based on the comparison. If the result is negative, then the object sorts less than the other; if 0, the two are equal, and if positive, this object sorts greater than the other. To translate this into boolean, simply performs object1.compareTo(object2) <op> object,  where op is one of <, <=, =, !=, >, or >=.

public int compareTo( Object o );

Implemented Classes: Classes implemented by this interface are Boolean, Byte, Character, Double, Enum, Float, Integer, Long, Short, String.

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 16, 2005

Related Tutorials

Discuss: Comparable Interface  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com