my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes compare() and compareTo() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "compare() and compareTo()" Watch "compare() and compareTo()" New topic
Author

compare() and compareTo()

vijay umar
Ranch Hand

Joined: Mar 24, 2009
Posts: 100
i am not clear about the difference between the compare() method and compareTo(); method,

what arguments it ttakes?
as far as i studied i have not understood the point that
compareto()--- we must modify the class whose instance we want to sort!! what does this mean?

and compare()---- we build a class seperate from the class whose instatnce we want to sort.! what does this mean?

can please give a good example to implement them?will be very helpful in understanding!
Ryan Beckett
Ranch Hand

Joined: Feb 22, 2009
Posts: 192
You got it. Here's an example to clarify your confusion.

vijay umar
Ranch Hand

Joined: Mar 24, 2009
Posts: 100
Thanks a lot ... nice exxample!

thus what i understood from the example is if we use comparator we need to do it with sepaerate class and if we use comparable we have to use in the same class which needs to be sorted? am i correct?

Then which is more advantageous?which should be used?
Ayan Kumar Roy
Greenhorn

Joined: Aug 21, 2002
Posts: 10
Very good example...indeed..!!


Ayan Kumar Roy.<br />India
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3673

vijay umar wrote:thus what i understood from the example is if we use comparator we need to do it with sepaerate class and if we use comparable we have to use in the same class which needs to be sorted? am i correct?
Then which is more advantageous?which should be used?


Using Comparator<V> gives you more flexibility (i.e: ability to sort the objects of the same class in any number of ways you want).


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: compare() and compareTo()
 
Similar Threads
Comparable and Comaparator
compareTo() and sort()
public static <T extends Comparable<? super T>> void sort(List<T> list)
Comparable vs Comparator
interface & Comparing Strings