dcsimg
Collections and Comparable
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   JavaPassion_Passion
Posted On:   Tuesday, July 31, 2007 10:26 AM

Hai all i am new to collections , so my doubt may seem silly to you , but plz help me as i am thinking a lot on it.


We can sort elements in a List implemented class ( for example ArrayList) using Collections.sort(List , Compartaor).
(I know how to work with comparator).

But what we have to do with Comparable interface .

I dont understand when is it required or for what purpose is this Comparable Interface is required .

Re: Collections and Comparable

Posted By:   Tim_Frith  
Posted On:   Tuesday, July 31, 2007 05:23 PM

You should read the detailed description provided in the javadoc for the Comparable interface.


Basically, implementing Comparable allows you to explicitly specify the "natural ordering" for a class.

Then you can sort it with Collections.sort(List).

Notice that the Comparator no longer needs to be specified because you've moved the compareTo() into your class.


Note that if you implement Comparable, you should also provide equals() and hashCode() methods in your class that are consistent with your compareTo(). In other words calling your class' equals() should always give true when your class' compareTo() returns 0. And hashCode() results for instances of your class should match where equals() is true.

I hope I said that last part right! Read the Comparable javadoc.

About | Sitemap | Contact