Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to compare to objects using comparator?  RSS feed

 
Bob Zoloman
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am trying to compare two object using comparator (not sure if I should use this or comparable - What is the difference?) Anyways, I implemented Comparator in the class, and wrote a method for compare, but I can't get the compareTo method to pop up in netbeans. I'm not sure what else I need to do to get this method to show up.


 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would be looking for compareTo() in whatever type "getBestMove()" returns, which you haven't told us. Does whatever that class is, have such a method?

In any case, you're not doing this quite right. "Comparable" is an interface that a class implements if you want to be able to compare one object to another, directly. If Foo implements Comparable, then you can write

if (aFoo.compareTo(anotherFoo) > 0) ...

On the other hand, Comparator is something that some OTHER class implements if you want to be able to compare two instances of your class using an instance of this second class; i.e.

FooComparator fc = ...
if (fc.compare(aFoo, anotherFoo) > 0) ...

The main reason Comparator is especially useful is that there is often more than one way to compare instances of a single class: you might sort Person objects by name, by address, by age... so you can define a NameComparator, an AddressComparator, and an AgeComparator. If you have Person implement Comparable, then you can only do it one way.

A lot of the Java Collections classes let you supply a Comparator to tell the collection how to sort the objects you put into the collection.

So anyway: in your case, either Turn should implement Comparable, and implement the compareTo() method; or otherwise, create a new class TurnComparator that implements Comparator and the compare() method. But you're mixing things up as it stands.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!