SCJP Certification

Sun Certified Java Programmer Certification exam essentials

September 25th, 2009

What is the comparable interface?

Java Facts, by Daisy Williams.

The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.

The Comparable interface in the generic form is written as follows:

interface Comparable, where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows

int i = object1.compareTo(object2)

  • If object1 < object2: The value of i returned will be negative.
  • If object1 > object2: The value of i returned will be positive.
  • If object1 = object2: The value of i returned will be zero.
Share

Back Top

Responses to “What is the comparable interface?”

Comments (0) Trackbacks (0) Leave a comment Trackback url
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

*