Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections

 
Abhishek Bose
Greenhorn
Posts: 24
Android Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Click this Link for difference between compareto and compare.
For compareTo example click this

P.S:Give appropriate heading.

Regards,
Sriram
 
Rajneesh K Rajput
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5790
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic