Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About Comparator Interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About Comparator Interface" Watch "About Comparator Interface" New topic
Author

About Comparator Interface

Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

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........


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9305
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Ankit Garg write :
..... your compareTo method .....
.

Is that compare() method or compareTo() method in the Comparator interface? I think, compare()???
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

The Comparator interface contains the compare method
The Comparable interface contains the compareTo Method


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Thanks Wouter Oet
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

You're welcome
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
but the compare method in Comparator makes use of compareTo method to do the comparison. That's why Ankit said compareTo method.


SCJP 1.6 96%
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Ok, Neha Daga.... Thanks....

BTW, Can you give me good example, ........
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
read comparator from K&B all the examples make use of it.
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

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