Here you can find the source of xor(boolean[] array)
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
Parameter | Description |
---|---|
array | an array of <code>boolean<code>s |
Parameter | Description |
---|---|
IllegalArgumentException | if <code>array</code> is empty. |
true
if the xor is successful.
public static boolean xor(boolean[] array)
//package com.java2s; /*/* w w w . j av a 2s .co m*/ $Id: BooleanUtils.java,v 1.3 2004-01-28 15:10:40 mvdb Exp $ Copyright 2002-2004 The Xulux Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Main { /** * <p>Performs an xor on a set of booleans.</p> * * <pre> * BooleanUtils.xor(new boolean[] { true, true }) = false * BooleanUtils.xor(new boolean[] { false, false }) = false * BooleanUtils.xor(new boolean[] { true, false }) = true * </pre> * * @param array an array of <code>boolean<code>s * @return <code>true</code> if the xor is successful. * @throws IllegalArgumentException if <code>array</code> is <code>null</code> * @throws IllegalArgumentException if <code>array</code> 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; } }