Returns true if odd number of elements are true otherwise false. - Java java.lang

Java examples for java.lang:boolean

Description

Returns true if odd number of elements are true otherwise false.

Demo Code



public class Main{
    private static final String NULL_ARRAY_MSG = "The Array must not be null";
    private static final String EMPTY_ARRAY_MSG = "Array is empty";
    private static final String NULL_VALUE_IN_ARRAY_MSG = "Array shouldn`t contain null objects";
    /**//from  w  w w  . ja  v  a 2s.c  om
     * Returns true if odd number of elements are true otherwise false.
     *
     * @exception java.lang.IllegalArgumentException for null or an empty array.
     */
    public static boolean xor(boolean[] values) {
        checkOnEmptyArray(values);
        boolean result = values[0];
        for (int i = 1; i < values.length; i++) {
            result = result ^ values[i];
        }
        return result;
    }
    /**
     * Returns true if odd number of elements are true otherwise false.
     *
     * @exception java.lang.IllegalArgumentException for null or an empty array or null value in the array.
     */
    public static boolean xor(Boolean[] values) {
        checkOnEmptyArray(values);
        Boolean result = values[0];
        for (int i = 1; i < values.length; i++) {
            result = result ^ values[i];
        }
        return result;
    }
    private static void checkOnEmptyArray(Boolean[] values) {
        if (values == null) {
            throw new IllegalArgumentException(NULL_ARRAY_MSG);
        }
        if (values.length == 0) {
            throw new IllegalArgumentException(EMPTY_ARRAY_MSG);
        }
        if (CollectionUtils.hasNull(values)) {
            throw new IllegalArgumentException(NULL_VALUE_IN_ARRAY_MSG);
        }
    }
    private static void checkOnEmptyArray(boolean[] values) {
        if (values == null) {
            throw new IllegalArgumentException(NULL_ARRAY_MSG);
        }
        if (values.length == 0) {
            throw new IllegalArgumentException(EMPTY_ARRAY_MSG);
        }
    }
}

Related Tutorials