• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About Comparator Interface

 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In K & B's book, it's said that....

..... you can use it to sort instances of any class. ...


My Question is : How it's possible?

(Can we compare by same fields of difference Class' instances)

Please Confirm? Thanks........
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The statement implies that you can use Comparator to sort instances of classes that don't implement Comparable. If you implement the type safe Comparator i.e. Comparator<Type>, then your compareTo method won't get instances of different class anyways...
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ankit Garg write :
..... your compareTo method .....
.

Is that compare() method or compareTo() method in the Comparator interface? I think, compare()???
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Comparator interface contains the compare method
The Comparable interface contains the compareTo Method
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Wouter Oet
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but the compare method in Comparator makes use of compareTo method to do the comparison. That's why Ankit said compareTo method.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, Neha Daga.... Thanks....

BTW, Can you give me good example, ........
 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
read comparator from K&B all the examples make use of it.
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neha Daga wrote:but the compare method in Comparator makes use of compareTo method to do the comparison. That's why Ankit said compareTo method.

That totally depends on the implementation. If I write an implementation of Comparator then it doesn't need to a Comparable implementation:


Ankit was refering to a type safe implementation. Like he said: Comparator i.e. Comparator<Type>
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic