aspose file tools*
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
Author

Collections

Abhishek Bose
Greenhorn

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.

Regards,
Sriram


For java examples,ebooks,interview questions,visit this blog
http://periodicupdates.blogspot.com/
Rajneesh K Rajput
Greenhorn

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.

Advantages:
- 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.)

Example:


This will give following output...
C
B
A
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collections