Win a copy of Terraform in Action this week in the Cloud forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Implementing Comparator interface

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic