• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Confusing Integer.max() method

 
Ranch Hand
Posts: 47
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi;)

I am more and more finishing my Preparation for the OCP Exam and I am very
confused with this Code:



Why does the second println() Statement print out 3?!?!

Shouldn't it get the max Value?

Kind regards
Florian
 
Bartender
Posts: 5465
212
  • Likes 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One of those trick questions, of which the amount seems to be infinite...

The 'stream.max' method takes a Comparator, in this case Comparator<Integer>.
Its method 'compare(int x, int y) returns a positive value if x > y, a negative value if x < y and 0 if x equals y.

Now look at your specific Comparator: compare(x, y) = Integer.max(x, y).
Since in your code x and y are positive, this "Integer.max" gives a positive result. That means that with this Comparator, x is always considered to be bigger than y when x > 0.

Can you now explain why the outcome of the second println is '3'?
 
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If the excellent and cow-worthy explanation of Piet doesn't ring a bell yet, you could add a println-statement to the lambda and see what happens... For example
 
Florian Jedamzik
Ranch Hand
Posts: 47
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you both!;)

Now I think I got it;)
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic