• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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: 15490
363
  • 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.
 
Attractive, successful people love this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic