1

The result of xor(true, true, true) of the BooleanUtils class under the commons-lang toolkit under Apache is false, but the result of System.out.println(true ^ true ^ true) is true. Why?

public class Test {
    public static void main(String[] args) {
        System.out.println(org.apache.commons.lang.BooleanUtils.xor(new boolean[]{true, true, true}));
        System.out.println(org.apache.commons.lang3.BooleanUtils.xor(new boolean[]{true, true, true}));
        System.out.println(true ^ true ^ true);
    }
}
/*
    result:
    false
    false
    true
*/
samabcde
  • 6,988
  • 2
  • 25
  • 41
mochen
  • 15
  • 3

1 Answers1

1

The most likely reason you are seeing this behavior is that you are using an older version of commons-lang (< 3.2).

Newer versions behave the same as Java (i.e. it evaluates one xor at a time from left to right).

The older versions used a different approach however: They return true only if there is exactly one true value in the entire array.

This behavior was considered incorrect (see LANG-921) and has since been fixed.

diredev
  • 138
  • 9
  • Thank you very much for your answer. I have checked the source code of this method from the latest [GitHub address](https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/BooleanUtils.java) and fixed the problem. – mochen Jul 30 '21 at 13:45
  • @mochen if this has answered your question then please mark it as accepted. – diredev Jul 31 '21 at 14:08