Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collections" Watch "Collections" New topic


Abhishek Bose

Joined: Dec 14, 2009
Posts: 24

What is the difference between compareTo() and compare().Both of them compares two objects then what is the actual difference... example required..!!
sri ramvaithiyanathan
Ranch Hand

Joined: Nov 20, 2010
Posts: 109
Click this Link for difference between compareto and compare.
For compareTo example click this

P.S:Give appropriate heading.


For java examples,ebooks,interview questions,visit this blog
Rajneesh K Rajput

Joined: Nov 14, 2009
Posts: 10
1. compareTo() takes just one argument.
If your class implements Comparable, i.e. you can only compare two of your same objects with one type of comparision logic.

2. Collects provides a mechanish for sorting by using Comparator interface.
This can be used in conjuction to create any no. of comparision logic, with any type of objects either in desc and asc order.

- You don't need to modify class code, which instance needs to be compared.
- You don't need to stick to one sorting logic and bind that with instances itself. (Covers in first step.)


This will give following output...
Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4624

A Comparator provides a general ordering mechanism. Some advantages have already been given.

You should always consider a Comparable however, if your class has a natural ordering. If from your class, it seems obvious how instances should be ordered, make your class to implement Comparable.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
I agree. Here's the link:
subject: Collections
It's not a secret anymore!