Operations on boolean primitives and Boolean objects.
* *This class tries to handle null
input gracefully.
* An exception will not be thrown for a null
input.
* Each method documents its behaviour in more detail.
Performs an xor on a set of booleans.
* ** BooleanUtils.xor(new boolean[] { true, true }) = false * BooleanUtils.xor(new boolean[] { false, false }) = false * BooleanUtils.xor(new boolean[] { true, false }) = true ** * @param array an array of
booleans
* @return true
if the xor is successful.
* @throws IllegalArgumentException if array
is null
* @throws IllegalArgumentException if array
is empty.
*/
public static boolean xor(boolean[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
// Loops through array, comparing each item
int trueCount = 0;
for (int i = 0; i < array.length; i++) {
// If item is true, and trueCount is < 1, increments count
// Else, xor fails
if (array[i]) {
if (trueCount < 1) {
trueCount++;
} else {
return false;
}
}
}
// Returns true if there was exactly 1 true item
return trueCount == 1;
}
/**
* Performs an xor on an array of Booleans.
*
*
* BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) = Boolean.FALSE
* BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE
* BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) = Boolean.TRUE
*
*
* @param array an array of Booleans
* @return true
if the xor is successful.
* @throws IllegalArgumentException if array
is null
* @throws IllegalArgumentException if array
is empty.
* @throws IllegalArgumentException if array
contains a null
*/
public static Boolean xor(Boolean[] array) {
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
boolean[] primitive = null;
try {
primitive = toPrimitive(array);
} catch (NullPointerException ex) {
throw new IllegalArgumentException("The array must not contain any null elements");
}
return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Converts an array of object Booleans to primitives.
*
* This method returns null
for a null
input array.
*
* @param array a Boolean
array, may be null
* @return a boolean
array, null
if null array input
* @throws NullPointerException if array content is null
*/
public static boolean[] toPrimitive(Boolean[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return new boolean[0];
}
final boolean[] result = new boolean[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].booleanValue();
}
return result;
}
}