[
https://issues.apache.org/jira/browse/LANG-922?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=13795492#comment-13795492
]
Benedikt Ritter commented on LANG-922:
--------------------------------------
Sample implementation:
{code:java}
/**
* <p>Checks if exactly one of the given booleans is true.</p>
*
* <pre>
* BooleanUtils.xor(true, true) = false
* BooleanUtils.xor(false, false) = false
* BooleanUtils.xor(true, false) = true
* BooleanUtils.xor(true, true) = false
* BooleanUtils.xor(false, false) = false
* BooleanUtils.xor(true, false) = true
* </pre>
*
* @param array an array of {@code boolean}s
* @return {@code true} if the array only contained true once.
* @throws IllegalArgumentException if {@code array} is {@code null}
* @throws IllegalArgumentException if {@code array} is empty.
* @since 3.2
*/
public static boolean isOneTrue(final boolean... array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
}
if (array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
// Loops through array, comparing each item
int trueCount = 0;
for (final boolean element : array) {
// If item is true, and trueCount is < 1, increments count
// Else, xor fails
if (element) {
if (trueCount < 1) {
trueCount++;
} else {
return false;
}
}
}
// Returns true if there was exactly 1 true item
return trueCount == 1;
}
{code}
> Add isOneTrue(booleans...) to BooleanUtils to preserve old behavior of
> BooleanUtils.xor(booleans...)
> ----------------------------------------------------------------------------------------------------
>
> Key: LANG-922
> URL: https://issues.apache.org/jira/browse/LANG-922
> Project: Commons Lang
> Issue Type: Bug
> Components: lang.*
> Reporter: Benedikt Ritter
> Fix For: 3.2
>
>
> The old implementation (prior to r1532476) of BooleanUtils.xor(boolean...)
> checked if the provided array contained exactly one boolean with value true.
> This was changed because it is not the correct behavior for an XOR operation.
> To preserve the behavior we should add BooleanUtils.isOneTrue(boolean...) and
> BooleanUtils.isOneTrue(Boolean...) (and possibly the equivalents for
> isOneFalse).
--
This message was sent by Atlassian JIRA
(v6.1#6144)