Java/Collections Data Structure/BitSet — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 07:27, 1 июня 2010

Another Bitset demo

  
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

/** Show various forms of nested classes.
* Not all nested classes are "inner classes".
*/
public class A extends Object {
  public class B {  // member class
    public class BB {
      public void print() {
        System.out.println("Hello from BB");
      }
    }
    public void print() {
      BB bb = new BB();
      bb.print();
    }
  }
  public void print() {
    class C {  // local class
    }
    Object d = new Object() {
      // anonymous inner class
    };
    System.out.println("Here are an A, a B, a C, and d.");
    System.out.println(this + " " + new B() + " " +
            new C() + " " + d);
    new B().print();
  }
  public static void main(String[] av) {
    new A().print();
  }
}





BitOHoney

  
import java.util.BitSet;
public class BitOHoney1 {
  public static void main(String args[]) {
    String names[] = { "Hershey"s Kisses", "Nestle"s Crunch", "Snickers",
        "3 Musketeers", "Milky Way", "Twix", "Mr. Goodbar", "Crunchie",
        "Godiva", "Charleston Chew", "Cadbury"s", "Lindt", "Aero",
        "Hebert", "Toberlone", "Smarties", "LifeSavers", "Riesen",
        "Goobers", "Raisenettes", "Nerds", "Tootsie Roll",
        "Sweet Tarts", "Cotton Candy" };
    BitSet bits = new BitSet();
    for (int i = 0, n = names.length; i < n; i++) {
      if ((names[i].length() % 2) == 0) {
        bits.set(i);
      }
    }
    System.out.println(bits);
    System.out.println("Size  : " + bits.size());
    System.out.println("Length: " + bits.length());
    for (int i = 0, n = names.length; i < n; i++) {
      if (!bits.get(i)) {
        System.out.println(names[i] + " is odd");
      }
    }
    BitSet bites = new BitSet();
    bites.set(0);
    bites.set(1);
    bites.set(2);
    bites.set(3);
    bites.andNot(bits);
    System.out.println(bites);
  }
}





BitOps

  
import java.util.BitSet;
public class BitOps {
  public static void main(String args[]) {
    BitSet set = new BitSet();
    set.set(1);
    set.set(2);
    set.set(3);
    set.set(4);
    set.set(5);
    System.out.println(set);
    BitSet set2 = new BitSet();
    set2.set(1);
    set2.set(3);
    set2.set(5);
    set2.set(7);
    BitSet set3 = (BitSet) set.clone();
    set3.and(set2);
    System.out.println(set3);
    set3 = (BitSet) set.clone();
    set3.or(set2);
    System.out.println(set3);
    set3 = (BitSet) set.clone();
    set3.xor(set2);
    System.out.println(set3);
    set3 = (BitSet) set.clone();
    set3.andNot(set2);
    System.out.println(set3);
    set3.andNot(null);
  }
}





Convert bitset to int array and string

  
import java.util.BitSet;
public class Main {
  public static void main(String[] args) {
    BitSet bs = new BitSet();
    bs.set(31);
    bs.set(15);
    bs.set(18);
    int[] intArray = bits2Ints(bs);
    for (int i = 0; i < intArray.length; i++)
      System.out.println(toBinary(intArray[i]));
  }
  static int[] bits2Ints(BitSet bs) {
    int[] temp = new int[bs.size() / 32];
    for (int i = 0; i < temp.length; i++)
      for (int j = 0; j < 32; j++)
        if (bs.get(i * 32 + j))
          temp[i] |= 1 << j;
    return temp;
  }
  static String toBinary(int num) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 32; i++) {
      sb.append(((num & 1) == 1) ? "1" : "0");
      num >>= 1;
    }
    return sb.reverse().toString();
  }
}





Implementation of a bit map of any size, together with static methods to manipulate int, byte and byte[] values as bit maps

    
 
/* Copyright (c) 2001-2009, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Implementation of a bit map of any size, together with static methods to
 * manipulate int, byte and byte[] values as bit maps.
 *
 * @author Fred Toussi (fredt@users dot sourceforge.net)
 * @version 1.9.0
 * @since 1.8.0
*/
public class BitMap {
    int   defaultCapacity;
    int   capacity;
    int[] map;
    int   limitPos;
    public BitMap(int initialCapacity) {
        int words = initialCapacity / 32;
        if (initialCapacity % 32 != 0) {
            words++;
        }
        defaultCapacity = capacity = words * 32;
        map             = new int[words];
        limitPos        = 0;
    }
    public int size() {
        return limitPos;
    }
    public void setSize(int size) {
        limitPos = size;
    }
    /**
     * Resets to blank with original capacity
     */
    public void reset() {
        map      = new int[defaultCapacity / 32];
        capacity = defaultCapacity;
        limitPos = 0;
    }
    /**
     * Sets pos and returns old value
     */
    public int set(int pos) {
        while (pos >= capacity) {
            doubleCapacity();
        }
        if (pos >= limitPos) {
            limitPos = pos + 1;
        }
        int windex = pos >> 5;
        int mask   = 0x80000000 >>> (pos & 0x1F);
        int word   = map[windex];
        int result = (word & mask) == 0 ? 0
                                        : 1;
        map[windex] = (word | mask);
        return result;
    }
    /**
     * Unsets pos and returns old value
     */
    public int unset(int pos) {
        while (pos >= capacity) {
            doubleCapacity();
        }
        if (pos >= limitPos) {
            limitPos = pos + 1;
            return 0;
        }
        int windex = pos >> 5;
        int mask   = 0x80000000 >>> (pos & 0x1F);
        int word   = map[windex];
        int result = (word & mask) == 0 ? 0
                                        : 1;
        mask        = ~mask;
        map[windex] = (word & mask);
        return result;
    }
    public int get(int pos) {
        while (pos >= capacity) {
            doubleCapacity();
        }
        if (pos >= limitPos) {
            limitPos = pos + 1;
            return 0;
        }
        int windex = pos >> 5;
        int mask   = 0x80000000 >>> (pos & 0x1F);
        int word   = map[windex];
        return (word & mask) == 0 ? 0
                                  : 1;
    }
    public boolean isSet(int pos) {
        return get(pos) == 1;
    }
    public byte[] getBytes() {
        byte[] buf = new byte[(limitPos + 7) / 8];
        if (buf.length == 0) {
            return buf;
        }
        for (int i = 0; ; ) {
            int v = map[i / 4];
            buf[i++] = (byte) (v >>> 24);
            if (i == buf.length) {
                break;
            }
            buf[i++] = (byte) (v >>> 16);
            if (i == buf.length) {
                break;
            }
            buf[i++] = (byte) (v >>> 8);
            if (i == buf.length) {
                break;
            }
            buf[i++] = (byte) v;
            if (i == buf.length) {
                break;
            }
        }
        return buf;
    }
    private void doubleCapacity() {
        int[] newmap = new int[map.length * 2];
        capacity *= 2;
        System.arraycopy(map, 0, newmap, 0, map.length);
        map = newmap;
    }
    /**
     * copy the byte value into the map at given position (0, 24)
     */
    public static int setByte(int map, byte value, int pos) {
        int intValue = (value & 0xff) << (24 - pos);
        int mask     = 0xff000000 >>> pos;
        mask = ~mask;
        map  &= mask;
        return (map | intValue);
    }
    public static int set(int map, int pos) {
        int mask = 0x80000000 >>> pos;
        return (map | mask);
    }
    public static byte set(byte map, int pos) {
        int mask = 0x00000080 >>> pos;
        return (byte) (map | mask);
    }
    public static int unset(int map, int pos) {
        int mask = 0x80000000 >>> pos;
        mask = ~mask;
        return (map & mask);
    }
    public static boolean isSet(int map, int pos) {
        int mask = 0x80000000 >>> pos;
        return (map & mask) == 0 ? false
                                 : true;
    }
    public static boolean isSet(byte map, int pos) {
        int mask = 0x00000080 >>> pos;
        return (map & mask) == 0 ? false
                                 : true;
    }
    public static boolean isSet(byte[] map, int pos) {
        int mask  = 0x00000080 >>> (pos & 0x07);;
        int index = pos / 8;
        if (index >= map.length) {
            return false;
        }
        byte b = map[index];
        return (b & mask) == 0 ? false
                               : true;
    }
    public static void unset(byte[] map, int pos) {
        int mask = 0x00000080 >>> (pos & 0x07);
        mask = ~mask;
        int index = pos / 8;
        if (index >= map.length) {
            return;
        }
        byte b = map[index];
        map[index] = (byte) (b & mask);
    }
    public static void set(byte[] map, int pos) {
        int mask  = 0x00000080 >>> (pos & 0x07);
        int index = pos / 8;
        if (index >= map.length) {
            return;
        }
        byte b = map[index];
        map[index] = (byte) (b | mask);
    }
    /**
     * AND count bits from source with map contents starting at pos
     */
    public static void and(byte[] map, int pos, byte source, int count) {
        int shift     = pos & 0x07;
        int mask      = (source & 0xff) >>> shift;
        int innermask = 0xff >> shift;
        int index     = pos / 8;
        if (count < 8) {
            innermask = innermask >>> (8 - count);
            innermask = innermask << (8 - count);
        }
        mask      &= innermask;
        innermask = ~innermask;
        if (index >= map.length) {
            return;
        }
        byte b = map[index];
        map[index] = (byte) (b & innermask);
        b          = (byte) (b & mask);
        map[index] = (byte) (map[index] | b);
        if (shift == 0) {
            return;
        }
        shift = 8 - shift;
        if (count > shift) {
            mask           = ((source & 0xff) << 8) >>> shift;
            innermask      = 0xff00 >>> shift;
            innermask      = ~innermask;
            b              = map[index + 1];
            map[index + 1] = (byte) (b & innermask);
            b              = (byte) (b & mask);
            map[index + 1] = (byte) (map[index + 1] | b);
        }
    }
    /**
     * OR count bits from source with map contents starting at pos
     */
    public static void or(byte[] map, int pos, byte source, int count) {
        int shift = pos & 0x07;
        int mask  = (source & 0xff) >>> shift;
        int index = pos / 8;
        if (index >= map.length) {
            return;
        }
        byte b = (byte) (map[index] | mask);
        map[index] = b;
        if (shift == 0) {
            return;
        }
        shift = 8 - shift;
        if (count > shift) {
            mask           = ((source & 0xff) << 8) >>> shift;
            b              = (byte) (map[index + 1] | mask);
            map[index + 1] = b;
        }
    }
    /**
     * overlay count bits from source on map contents starting at pos
     */
    public static void overlay(byte[] map, int pos, byte source, int count) {
        int shift     = pos & 0x07;
        int mask      = (source & 0xff) >>> shift;
        int innermask = 0xff >> shift;
        int index     = pos / 8;
        if (count < 8) {
            innermask = innermask >>> (8 - count);
            innermask = innermask << (8 - count);
        }
        mask      &= innermask;
        innermask = ~innermask;
        if (index >= map.length) {
            return;
        }
        byte b = map[index];
        b          = (byte) (b & innermask);
        map[index] = (byte) (b | mask);
        if (shift == 0) {
            return;
        }
        shift = 8 - shift;
        if (count > shift) {
            mask           = ((source & 0xff) << 8) >>> shift;
            innermask      = 0xff00 >>> shift;
            innermask      = ~innermask;
            b              = map[index + 1];
            b              = (byte) (b & innermask);
            map[index + 1] = (byte) (b | mask);
        }
    }
    public static int compare(byte[] a, byte[] b) {
        int shortLength = a.length > b.length ? b.length
                                              : a.length;
        for (int i = 0; i < shortLength; i++) {
            if (a[i] == b[i]) {
                continue;
            }
            return (((int) a[i]) & 0xff) > (((int) b[i]) & 0xff) ? 1
                                                                 : -1;
        }
        if (a.length == b.length) {
            return 0;
        }
        return a.length > b.length ? 1
                                   : -1;
    }
    public static byte[] and(byte[] a, byte[] b) {
        int    length      = a.length > b.length ? a.length
                                                 : b.length;
        int    shortLength = a.length > b.length ? b.length
                                                 : a.length;
        byte[] map         = new byte[length];
        for (int i = 0; i < shortLength; i++) {
            map[i] = (byte) (a[i] & b[i]);
        }
        return map;
    }
    public static byte[] or(byte[] a, byte[] b) {
        int    length      = a.length > b.length ? a.length
                                                 : b.length;
        int    shortLength = a.length > b.length ? b.length
                                                 : a.length;
        byte[] map         = new byte[length];
        if (length != shortLength) {
            byte[] source = a.length > b.length ? a
                                                : b;
            System.arraycopy(source, shortLength, map, shortLength,
                             length - shortLength);
        }
        for (int i = 0; i < shortLength; i++) {
            map[i] = (byte) (a[i] | b[i]);
        }
        return map;
    }
    public static byte[] xor(byte[] a, byte[] b) {
        int    length      = a.length > b.length ? a.length
                                                 : b.length;
        int    shortLength = a.length > b.length ? b.length
                                                 : a.length;
        byte[] map         = new byte[length];
        if (length != shortLength) {
            byte[] source = a.length > b.length ? a
                                                : b;
            System.arraycopy(source, shortLength, map, shortLength,
                             length - shortLength);
        }
        for (int i = 0; i < shortLength; i++) {
            map[i] = (byte) (a[i] ^ b[i]);
        }
        return map;
    }
    public static byte[] not(byte[] a) {
        byte[] map = new byte[a.length];
        for (int i = 0; i < a.length; i++) {
            map[i] = (byte) ~a[i];
        }
        return map;
    }
    public static boolean hasAnyBitSet(byte[] map) {
        for (int i = 0; i < map.length; i++) {
            if (map[i] != 0) {
                return true;
            }
        }
        return false;
    }
    public static byte[] leftShift(byte[] map, int shiftBits) {
        byte[] newMap     = new byte[map.length];
        int    shiftBytes = shiftBits / 8;
        if (shiftBytes >= map.length) {
            return newMap;
        }
        shiftBits = shiftBits % 8;
        if (shiftBits == 0) {
            for (int i = 0, j = shiftBytes; j < map.length; i++, j++) {
                newMap[i] = map[j];
            }
        } else {
            for (int i = 0, j = shiftBytes; j < map.length; i++, j++) {
                int shifted = (map[j] & 0xff) << shiftBits;
                newMap[i] = (byte) shifted;
                if (i > 0) {
                    newMap[i - 1] |= (byte) (shifted >>> 8);
                }
            }
        }
        return newMap;
    }
}





Java 1.5 (5.0) Changes to the API: several of the new bit manipulation methods in Integer.

  
public class Bits { 
  public static void main(String args[]) { 
    int n = 170; // 10101010 
    System.out.println("Value in binary: 10101010"); 
 
    System.out.println("Number of one bits: " + Integer.bitCount(n)); 
 
    System.out.println("Highest one bit: " + Integer.highestOneBit(n)); 
 
    System.out.println("Lowest one bit: " + Integer.lowestOneBit(n)); 
 
    System.out.println("Number of leading zeros : " + Integer.numberOfLeadingZeros(n)); 
 
    System.out.println("Number of trailing zeros : " +Integer.numberOfTrailingZeros(n)); 
 
    System.out.println("\nBeginning with the value 1, " + "rotate left 16 times."); 
    n = 1; 
    for(int i=0; i < 16; i++) { 
      n = Integer.rotateLeft(n, 1); 
      System.out.println(n); 
    } 
  } 
}





Manipulating the BitSet

  
import java.util.BitSet;
public class TwoBitPlanets {
  public static void main(String args[]) {
    String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter",
        "Saturn", "Uranus", "Neptune", "Pluto" };
    int moons[] = { 0, 0, 1, 2, 16, 18, 17, 8, 1 };
    int namesLen = names.length;
    BitSet bits = new BitSet(namesLen);
    for (int i = 0; i < namesLen; i++) {
      if ((moons[i] % 2) == 0) {
        bits.set(i);
      }
    }
    for (int i = 0; i < namesLen; i++) {
      System.out.println(names[i] + " Even # Moons (" + moons[i] + ")? "
          + bits.get(i));
    }
  }
}





Operations on bit-mapped fields.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
/**
 * <p>Operations on bit-mapped fields.</p>
 *
 * @author Apache Jakarta POI
 * @author Scott Sanders (sanders at apache dot org)
 * @author Marc Johnson (mjohnson at apache dot org)
 * @author Andrew C. Oliver (acoliver at apache dot org)
 * @author Stephen Colebourne
 * @author Pete Gieser
 * @author Gary Gregory
 * @since 2.0
 * @version $Id: BitField.java 437554 2006-08-28 06:21:41Z bayard $
 */
public class BitField {
    
    private final int _mask;
    private final int _shift_count;
    /**
     * <p>Creates a BitField instance.</p>
     *
     * @param mask the mask specifying which bits apply to this
     *  BitField. Bits that are set in this mask are the bits
     *  that this BitField operates on
     */
    public BitField(int mask) {
        _mask = mask;
        int count = 0;
        int bit_pattern = mask;
        if (bit_pattern != 0) {
            while ((bit_pattern & 1) == 0) {
                count++;
                bit_pattern >>= 1;
            }
        }
        _shift_count = count;
    }
    /**
     * <p>Obtains the value for the specified BitField, appropriately
     * shifted right.</p>
     *
     * <p>Many users of a BitField will want to treat the specified
     * bits as an int value, and will not want to be aware that the
     * value is stored as a BitField (and so shifted left so many
     * bits).</p>
     *
     * @see #setValue(int,int)
     * @param holder the int data containing the bits we"re interested
     *  in
     * @return the selected bits, shifted right appropriately
     */
    public int getValue(int holder) {
        return getRawValue(holder) >> _shift_count;
    }
    /**
     * <p>Obtains the value for the specified BitField, appropriately
     * shifted right, as a short.</p>
     *
     * <p>Many users of a BitField will want to treat the specified
     * bits as an int value, and will not want to be aware that the
     * value is stored as a BitField (and so shifted left so many
     * bits).</p>
     *
     * @see #setShortValue(short,short)
     * @param holder the short data containing the bits we"re
     *  interested in
     * @return the selected bits, shifted right appropriately
     */
    public short getShortValue(short holder) {
        return (short) getValue(holder);
    }
    /**
     * <p>Obtains the value for the specified BitField, unshifted.</p>
     *
     * @param holder the int data containing the bits we"re
     *  interested in
     * @return the selected bits
     */
    public int getRawValue(int holder) {
        return holder & _mask;
    }
    /**
     * <p>Obtains the value for the specified BitField, unshifted.</p>
     *
     * @param holder the short data containing the bits we"re
     *  interested in
     * @return the selected bits
     */
    public short getShortRawValue(short holder) {
        return (short) getRawValue(holder);
    }
    /**
     * <p>Returns whether the field is set or not.</p>
     *
     * <p>This is most commonly used for a single-bit field, which is
     * often used to represent a boolean value; the results of using
     * it for a multi-bit field is to determine whether *any* of its
     * bits are set.</p>
     *
     * @param holder the int data containing the bits we"re interested
     *  in
     * @return <code>true</code> if any of the bits are set,
     *  else <code>false</code>
     */
    public boolean isSet(int holder) {
        return (holder & _mask) != 0;
    }
    /**
     * <p>Returns whether all of the bits are set or not.</p>
     *
     * <p>This is a stricter test than {@link #isSet(int)},
     * in that all of the bits in a multi-bit set must be set
     * for this method to return <code>true</code>.</p>
     *
     * @param holder the int data containing the bits we"re
     *  interested in
     * @return <code>true</code> if all of the bits are set,
     *  else <code>false</code>
     */
    public boolean isAllSet(int holder) {
        return (holder & _mask) == _mask;
    }
    /**
     * <p>Replaces the bits with new values.</p>
     *
     * @see #getValue(int)
     * @param holder the int data containing the bits we"re
     *  interested in
     * @param value the new value for the specified bits
     * @return the value of holder with the bits from the value
     *  parameter replacing the old bits
     */
    public int setValue(int holder, int value) {
        return (holder & ~_mask) | ((value << _shift_count) & _mask);
    }
    /**
     * <p>Replaces the bits with new values.</p>
     *
     * @see #getShortValue(short)
     * @param holder the short data containing the bits we"re
     *  interested in
     * @param value the new value for the specified bits
     * @return the value of holder with the bits from the value
     *  parameter replacing the old bits
     */
    public short setShortValue(short holder, short value) {
        return (short) setValue(holder, value);
    }
    /**
     * <p>Clears the bits.</p>
     *
     * @param holder the int data containing the bits we"re
     *  interested in
     * @return the value of holder with the specified bits cleared
     *  (set to <code>0</code>)
     */
    public int clear(int holder) {
        return holder & ~_mask;
    }
    /**
     * <p>Clears the bits.</p>
     *
     * @param holder the short data containing the bits we"re
     *  interested in
     * @return the value of holder with the specified bits cleared
     *  (set to <code>0</code>)
     */
    public short clearShort(short holder) {
        return (short) clear(holder);
    }
    /**
     * <p>Clears the bits.</p>
     *
     * @param holder the byte data containing the bits we"re
     *  interested in
     *
     * @return the value of holder with the specified bits cleared
     *  (set to <code>0</code>)
     */
    public byte clearByte(byte holder) {
        return (byte) clear(holder);
    }
    /**
     * <p>Sets the bits.</p>
     *
     * @param holder the int data containing the bits we"re
     *  interested in
     * @return the value of holder with the specified bits set
     *  to <code>1</code>
     */
    public int set(int holder) {
        return holder | _mask;
    }
    /**
     * <p>Sets the bits.</p>
     *
     * @param holder the short data containing the bits we"re
     *  interested in
     * @return the value of holder with the specified bits set
     *  to <code>1</code>
     */
    public short setShort(short holder) {
        return (short) set(holder);
    }
    /**
     * <p>Sets the bits.</p>
     *
     * @param holder the byte data containing the bits we"re
     *  interested in
     *
     * @return the value of holder with the specified bits set
     *  to <code>1</code>
     */
    public byte setByte(byte holder) {
        return (byte) set(holder);
    }
    /**
     * <p>Sets a boolean BitField.</p>
     *
     * @param holder the int data containing the bits we"re
     *  interested in
     * @param flag indicating whether to set or clear the bits
     * @return the value of holder with the specified bits set or
     *         cleared
     */
    public int setBoolean(int holder, boolean flag) {
        return flag ? set(holder) : clear(holder);
    }
    /**
     * <p>Sets a boolean BitField.</p>
     *
     * @param holder the short data containing the bits we"re
     *  interested in
     * @param flag indicating whether to set or clear the bits
     * @return the value of holder with the specified bits set or
     *  cleared
     */
    public short setShortBoolean(short holder, boolean flag) {
        return flag ? setShort(holder) : clearShort(holder);
    }
    /**
     * <p>Sets a boolean BitField.</p>
     *
     * @param holder the byte data containing the bits we"re
     *  interested in
     * @param flag indicating whether to set or clear the bits
     * @return the value of holder with the specified bits set or
     *  cleared
     */
    public byte setByteBoolean(byte holder, boolean flag) {
        return flag ? setByte(holder) : clearByte(holder);
    }
}





Operations on series of numbers

  
import java.util.BitSet;
public class NumSeries {
  public static void main(String[] args) {
    for (int i = 1; i <= months.length; i++)
      System.out.println("Month # " + i);
  
    for (int i = 0; i < months.length; i++)
      System.out.println("Month " + months[i]);
    BitSet b = new BitSet();
    b.set(0);  // January
    b.set(3);  // April
    for (int i = 0; i<months.length; i++) {
      if (b.get(i))
        System.out.println("Month " + months[i] + " requested");
    }
  }
  /** The names of the months. See Dates/Times chapter for a better way */
  protected static String months[] = {
    "January", "February", "March", "April",
    "May", "June", "July", "August",
    "September", "October", "November", "December"
  };
}





The use of BitSet

  
import java.util.BitSet;
public class BitOHoney {
  public static void main(String args[]) {
    String names[] = { "Java", "Source", "and",
        "Support"};
    BitSet bits = new BitSet();
    for (int i = 0, n = names.length; i < n; i++) {
      if ((names[i].length() % 2) == 0) {
        bits.set(i);
      }
    }
    System.out.println(bits);
    System.out.println("Size : " + bits.size());
    System.out.println("Length: " + bits.length());
    for (int i = 0, n = names.length; i < n; i++) {
      if (!bits.get(i)) {
        System.out.println(names[i] + " is odd");
      }
    }
    BitSet bites = new BitSet();
    bites.set(0);
    bites.set(1);
    bites.set(2);
    bites.set(3);
    bites.andNot(bits);
    System.out.println(bites);
  }
}