Reputation: 4241
I was implementing an N-nary tree (here N=4) and want to put in a logic to do something if the boolean property val
of all four children of a node are equal, I tried with:
if (childOne.val == childTwo.val == childThree.val == childFour.val){
doSomthing();
}
however this doesn't work for my test cases, so I have to change it to a more explicit and verbose:
if (childOne.val == childTwo.val && childTwo.val == childThree.val && childThree.val == childFour.val){
doSomthing();
}
and this one works. However I cannot make sense why the first evaluation doesn't give me the correct answer.
Upvotes: 1
Views: 170
Reputation: 271050
The ==
operator is left associative, so your first expression looks like this with brackets added:
(((childOne.val == childTwo.val) == childThree.val) == childFour.val)
Here's a case where the above will be true, but not all four values are the same:
Another way of doing this:
Stream.of(childOne.val, childTwo.val, childThree.val, childFour.val)
.distinct().count() == 1
I suggest you stick with the plain old &&
because there isn't a BooleanStream
and the booleans need to be boxed.
Upvotes: 4