• Post Reply Bookmark Topic Watch Topic
  • New Topic

Confusing Integer.max() method  RSS feed

 
Florian Jedamzik
Ranch Hand
Posts: 47
3
  • Mark post as helpful
  • send pies
  • 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
 
Piet Souris
Rancher
Posts: 1843
61
  • Likes 3
  • Mark post as helpful
  • send pies
  • 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'?
 
Roel De Nijs
Sheriff
Posts: 11095
173
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thank you both!;)

Now I think I got it;)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!