• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Collections

 
Greenhorn
Posts: 24
Android Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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..!!
 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Saloon Keeper
Posts: 14502
325
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Popeye has his spinach. I have this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic