Diff between Comparator and Comparable
4 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Srikanth_B
Posted On:   Monday, July 5, 2004 03:13 AM



Hi




Could some one let me know the diff between the Comparator interface and Comparable interface.






I only understand that Comparator is from java.lang and Comparable is from java.util.






The parameters are different






Thanx in advance



Srikanth

Re: Diff between Comparator and Comparable

Posted By:   Dale_DeMott  
Posted On:   Tuesday, July 6, 2004 08:10 AM

The Comparable interface allows you to compare yourself (this) with another like object. This forces the object itself to know how to sort itself.

With the Comparator you can compare two objects that are alike. The objects that are being compared do not have to know how to sort themselves. The object that implements Comparator has to know that. This actually gives you the ability to have several different ways to sort.

Re: Diff between Comparator and Comparable

Posted By:   kishore_kollipara  
Posted On:   Monday, July 5, 2004 10:18 PM

I obeserved that functionality of both are same.Comparable imposes some natural ordering on objects which a class implements.It belongs to java.lang.package.Comparator also do the same thing.It belongs to java.util package.

you can compare the objects by using comparator and comparable.

Re: Diff between Comparator and Comparable

Posted By:   Sean_Owen  
Posted On:   Monday, July 5, 2004 05:28 PM

An implemenation of either interfaces defines an ordering on Objects.



A class may implement Comparable to define a "natural ordering" of objects of its class. Comparable requires you to implement a compareTo() method which compares the object itself to another object. Implementing Cloneable is appropriate and useful when there is a clear default ordering for objects of that class -- for example, Date and Integer.



Comparator implementations also compare objects but are separate from the classes that they compare. That's why Comparator asks you to define a method compare() that takes two objects to compare. Comparator implementations can define any ordering you like. They are appropriate when you need to compare instances of a class that does not define a "natural ordering" (i.e. does not implement Cloneable), or when you want to use an ordering besides the natural ordering. For example, you may want to sort Integer objects in descending rather than ascending order. For this you would define a Comparator.

Re: Diff between Comparator and Comparable

Posted By:   Srikanth_B  
Posted On:   Monday, July 5, 2004 03:14 AM



Sorry for the messup in the packages
Comparator - util and Comparable from - lang

About | Sitemap | Contact