Chen Xie
Chen Xie

Reputation: 4241

Java evaluate if multiple boolean parameters are equal

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

Answers (1)

Sweeper
Sweeper

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:

  • child 1 and 2 are false
  • child 3 and 4 are true

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

Related Questions