views:

145

answers:

2

in which situations we have to implement the Comparable interface?

+6  A: 

When you want to be able to compare 2 objects and get a result of equal, less than, or greater than.

Implementing Comparable gives your objects a compareTo method. If you add them to a sorted list then they will automatically be sorted based on what your compareTo method returns.

It's pretty basic. I don't know what else there is to add.

takteek
To expand on takteek's answer, basically, you'll need to implement the Comparable interface to use most of the built-in sorting functionality for various sorted collections.
Amber
or can we say we have to use it for the collection which is unsorted and unordered and we want to find the index of the specified element of that collection(like HashMap collection)????
Johanna
The Comparable interface specifies what is known as the "natural" ordering of the objects.
Michael Wiles
Johanna: You don't need to implement it for hastables, since they go by the hash code
Chad Okere
Chad Okere:also for HashMap???
Johanna
A: 

When your class implement the Comparable interface, you have to implement the compareTo() method in a way that you can clearly tell where an instance of your class would go in an ordered list of such instances.

Implementing efficient sorting algorithms and ordered collections isn't trivial. Therefore you would do this when you want objects of a class to have natural ordering, so you can use the proven sorting and order-dependent algorithms and classes provided by Java instead of implementing your own, like having the contents of a TreeSet remain ordered after insertions/deletions, or using Collections.sort().

Munir