Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2008 The Guava Authors
   *
   * 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.
  */
 
 package com.google.common.primitives;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkElementIndex;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkPositionIndexes;
 
 
 import java.util.List;
Static utility methods pertaining to boolean primitives, that are not already found in either java.lang.Boolean or java.util.Arrays.

See the Guava User Guide article on primitive utilities.

Author(s):
Kevin Bourrillion
Since:
1.0
 
 public final class Booleans {
   private Booleans() {}

  
Returns a hash code for value; equal to the result of invoking ((Boolean) value).hashCode().

Parameters:
value a primitive boolean value
Returns:
a hash code for the value
 
   public static int hashCode(boolean value) {
     return value ? 1231 : 1237;
   }

  
Compares the two specified boolean values in the standard way (false is considered less than true). The sign of the value returned is the same as that of ((Boolean) a).compareTo(b).

Parameters:
a the first boolean to compare
b the second boolean to compare
Returns:
a positive number if only a is true, a negative number if only b is true, or zero if a == b
 
   public static int compare(boolean aboolean b) {
     return (a == b) ? 0 : (a ? 1 : -1);
   }

  
Returns true if target is present as an element anywhere in array.

Note: consider representing the array as a java.util.BitSet instead, replacing Booleans.contains(array, true) with !bitSet.isEmpty() and Booleans.contains(array, false) with bitSet.nextClearBit(0) == sizeOfBitSet.

Parameters:
array an array of boolean values, possibly empty
target a primitive boolean value
Returns:
true if array[i] == target for some value of i
 
   public static boolean contains(boolean[] arrayboolean target) {
     for (boolean value : array) {
       if (value == target) {
         return true;
       }
     }
     return false;
   }

  
Returns the index of the first appearance of the value target in array.

Note: consider representing the array as a java.util.BitSet instead, and using java.util.BitSet.nextSetBit(int) or java.util.BitSet.nextClearBit(int).

Parameters:
array an array of boolean values, possibly empty
target a primitive boolean value
Returns:
the least index i for which array[i] == target, or -1 if no such index exists.
  public static int indexOf(boolean[] arrayboolean target) {
    return indexOf(arraytarget, 0, array.length);
  }
  // TODO(kevinb): consider making this public
  private static int indexOf(
      boolean[] arrayboolean targetint startint end) {
    for (int i = starti < endi++) {
      if (array[i] == target) {
        return i;
      }
    }
    return -1;
  }

  
Returns the start position of the first occurrence of the specified target within array, or -1 if there is no such occurrence.

More formally, returns the lowest index i such that java.util.Arrays.copyOfRange(array, i, i + target.length) contains exactly the same elements as target.

Parameters:
array the array to search for the sequence target
target the array to search for as a sub-sequence of array
  public static int indexOf(boolean[] arrayboolean[] target) {
    checkNotNull(array"array");
    checkNotNull(target"target");
    if (target.length == 0) {
      return 0;
    }
    outer:
    for (int i = 0; i < array.length - target.length + 1; i++) {
      for (int j = 0; j < target.lengthj++) {
        if (array[i + j] != target[j]) {
          continue outer;
        }
      }
      return i;
    }
    return -1;
  }

  
Returns the index of the last appearance of the value target in array.

Parameters:
array an array of boolean values, possibly empty
target a primitive boolean value
Returns:
the greatest index i for which array[i] == target, or -1 if no such index exists.
  public static int lastIndexOf(boolean[] arrayboolean target) {
    return lastIndexOf(arraytarget, 0, array.length);
  }
  // TODO(kevinb): consider making this public
  private static int lastIndexOf(
      boolean[] arrayboolean targetint startint end) {
    for (int i = end - 1; i >= starti--) {
      if (array[i] == target) {
        return i;
      }
    }
    return -1;
  }

  
Returns the values from each provided array combined into a single array. For example, concat(new boolean[] {a, b, new boolean[] {}, new boolean[] {c}} returns the array {a, b, c}.

Parameters:
arrays zero or more boolean arrays
Returns:
a single array containing all the values from the source arrays, in order
  public static boolean[] concat(boolean[]... arrays) {
    int length = 0;
    for (boolean[] array : arrays) {
      length += array.length;
    }
    boolean[] result = new boolean[length];
    int pos = 0;
    for (boolean[] array : arrays) {
      System.arraycopy(array, 0, resultposarray.length);
      pos += array.length;
    }
    return result;
  }

  
Returns an array containing the same values as array, but guaranteed to be of a specified minimum length. If array already has a length of at least minLength, it is returned directly. Otherwise, a new array of size minLength + padding is returned, containing the values of array, and zeroes in the remaining places.

Parameters:
array the source array
minLength the minimum length the returned array must guarantee
padding an extra amount to "grow" the array by if growth is necessary
Returns:
an array containing the values of array, with guaranteed minimum length minLength
Throws:
java.lang.IllegalArgumentException if minLength or padding is negative
  public static boolean[] ensureCapacity(
      boolean[] arrayint minLengthint padding) {
    checkArgument(minLength >= 0, "Invalid minLength: %s"minLength);
    checkArgument(padding >= 0, "Invalid padding: %s"padding);
    return (array.length < minLength)
        ? copyOf(arrayminLength + padding)
        : array;
  }
  // Arrays.copyOf() requires Java 6
  private static boolean[] copyOf(boolean[] originalint length) {
    boolean[] copy = new boolean[length];
    System.arraycopy(original, 0, copy, 0, Math.min(original.lengthlength));
    return copy;
  }

  
Returns a string containing the supplied boolean values separated by separator. For example, join("-", false, true, false) returns the string "false-true-false".

Parameters:
separator the text that should appear between consecutive values in the resulting string (but not at the start or end)
array an array of boolean values, possibly empty
  public static String join(String separatorboolean... array) {
    checkNotNull(separator);
    if (array.length == 0) {
      return "";
    }
    // For pre-sizing a builder, just get the right order of magnitude
    StringBuilder builder = new StringBuilder(array.length * 7);
    builder.append(array[0]);
    for (int i = 1; i < array.lengthi++) {
      builder.append(separator).append(array[i]);
    }
    return builder.toString();
  }

  
Returns a comparator that compares two boolean arrays lexicographically. That is, it compares, using compare(boolean,boolean)), the first pair of values that follow any common prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For example, [] < [false] < [false, true] < [true].

The returned comparator is inconsistent with java.lang.Object.equals(java.lang.Object) (since arrays support only identity equality), but it is consistent with java.util.Arrays.equals(boolean[],boolean[]).

Since:
2.0
See also:
Lexicographical order article at Wikipedia
  public static Comparator<boolean[]> lexicographicalComparator() {
  }
  private enum LexicographicalComparator implements Comparator<boolean[]> {
    INSTANCE;
    @Override
    public int compare(boolean[] leftboolean[] right) {
      int minLength = Math.min(left.lengthright.length);
      for (int i = 0; i < minLengthi++) {
        int result = Booleans.compare(left[i], right[i]);
        if (result != 0) {
          return result;
        }
      }
      return left.length - right.length;
    }
  }

  
Copies a collection of Boolean instances into a new array of primitive boolean values.

Elements are copied from the argument collection as if by collection.toArray(). Calling this method is as thread-safe as calling that method.

Note: consider representing the collection as a java.util.BitSet instead.

Parameters:
collection a collection of Boolean objects
Returns:
an array containing the same values as collection, in the same order, converted to primitives
Throws:
java.lang.NullPointerException if collection or any of its elements is null
  public static boolean[] toArray(Collection<Booleancollection) {
    if (collection instanceof BooleanArrayAsList) {
      return ((BooleanArrayAsListcollection).toBooleanArray();
    }
    Object[] boxedArray = collection.toArray();
    int len = boxedArray.length;
    boolean[] array = new boolean[len];
    for (int i = 0; i < leni++) {
      // checkNotNull for GWT (do not optimize)
      array[i] = (BooleancheckNotNull(boxedArray[i]);
    }
    return array;
  }

  
Returns a fixed-size list backed by the specified array, similar to java.util.Arrays.asList(java.lang.Object[]). The list supports java.util.List.set(int,java.lang.Object), but any attempt to set a value to null will result in a java.lang.NullPointerException.

The returned list maintains the values, but not the identities, of Boolean objects written to or read from it. For example, whether list.get(0) == list.get(0) is true for the returned list is unspecified.

Parameters:
backingArray the array to back the list
Returns:
a list view of the array
  public static List<BooleanasList(boolean... backingArray) {
    if (backingArray.length == 0) {
      return Collections.emptyList();
    }
    return new BooleanArrayAsList(backingArray);
  }
  private static class BooleanArrayAsList extends AbstractList<Boolean>
      implements RandomAccessSerializable {
    final boolean[] array;
    final int start;
    final int end;
    BooleanArrayAsList(boolean[] array) {
      this(array, 0, array.length);
    }
    BooleanArrayAsList(boolean[] arrayint startint end) {
      this. = array;
      this. = start;
      this. = end;
    }
    @Override public int size() {
      return  - ;
    }
    @Override public boolean isEmpty() {
      return false;
    }
    @Override public Boolean get(int index) {
      checkElementIndex(indexsize());
      return [ + index];
    }
    @Override public boolean contains(Object target) {
      // Overridden to prevent a ton of boxing
      return (target instanceof Boolean)
          && Booleans.indexOf(, (Booleantarget) != -1;
    }
    @Override public int indexOf(Object target) {
      // Overridden to prevent a ton of boxing
      if (target instanceof Boolean) {
        int i = Booleans.indexOf(, (Booleantarget);
        if (i >= 0) {
          return i - ;
        }
      }
      return -1;
    }
    @Override public int lastIndexOf(Object target) {
      // Overridden to prevent a ton of boxing
      if (target instanceof Boolean) {
        int i = Booleans.lastIndexOf(, (Booleantarget);
        if (i >= 0) {
          return i - ;
        }
      }
      return -1;
    }
    @Override public Boolean set(int indexBoolean element) {
      checkElementIndex(indexsize());
      boolean oldValue = [ + index];
      // checkNotNull for GWT (do not optimize)
      [ + index] = checkNotNull(element);
      return oldValue;
    }
    @Override public List<BooleansubList(int fromIndexint toIndex) {
      int size = size();
      checkPositionIndexes(fromIndextoIndexsize);
      if (fromIndex == toIndex) {
        return Collections.emptyList();
      }
      return new BooleanArrayAsList( + fromIndex + toIndex);
    }
    @Override public boolean equals(Object object) {
      if (object == this) {
        return true;
      }
      if (object instanceof BooleanArrayAsList) {
        BooleanArrayAsList that = (BooleanArrayAsListobject;
        int size = size();
        if (that.size() != size) {
          return false;
        }
        for (int i = 0; i < sizei++) {
          if ([ + i] != that.array[that.start + i]) {
            return false;
          }
        }
        return true;
      }
      return super.equals(object);
    }
    @Override public int hashCode() {
      int result = 1;
      for (int i = i < i++) {
        result = 31 * result + Booleans.hashCode([i]);
      }
      return result;
    }
    @Override public String toString() {
      StringBuilder builder = new StringBuilder(size() * 7);
      builder.append([] ? "[true" : "[false");
      for (int i =  + 1; i < i++) {
        builder.append([i] ? ", true" : ", false");
      }
      return builder.append(']').toString();
    }
    boolean[] toBooleanArray() {
      // Arrays.copyOfRange() is not available under GWT
      int size = size();
      boolean[] result = new boolean[size];
      System.arraycopy(result, 0, size);
      return result;
    }
    private static final long serialVersionUID = 0;
  }
New to GrepCode? Check out our FAQ X