• Post Reply Bookmark Topic Watch Topic
  • New Topic

Implementing Comparator interface  RSS feed

 
Lira Mandel
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What particularly confuses me the most is the overriding of the compare method.

Here's an example I found:



1. In the compare method, what happens when it returns one of the 0, -1, or 1? How does returning such values contribute to the sorting process? How does it take in information (like I know it does through the parameters, but how exactly)?
2. Why do we use the class name for the generics?
3. Additional significant information aside from the answers to my questions above would be hugely appreciated!
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lira Mandel wrote:1. In the compare method, what happens when it returns one of the 0, -1, or 1? How does returning such values contribute to the sorting process? How does it take in information (like I know it does through the parameters, but how exactly)?

Think about what a "sort" does. It orders a set of items in a specific way. So, in order to do that, it needs to know, given TWO (and only two) items, which one is greater than the other (or if they're equal). Since there are 3 possible outcomes to such a test (a > b, a == b, and a < b), the method returns those results as positive (Note: NOT necessarily 1), 0, and negative. The Comparator does that part, the sort algorithm takes care of the rest.

2. Why do we use the class name for the generics?

Because the Comparator needs to know what kind of items to expect for its compare() method. If you need further explanation, I suggest you look at the tutorials.

3. Additional significant information aside from the answers to my questions above would be hugely appreciated!

Not sure how much I can add. Hopefully the above helps.

Winston

PS: Welcome to the Ranch.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!