BitSet
About
The BitSet class in Java is a part of the java.util package and provides an efficient way to work with a sequence of bits. It represents a vector of bits that grows dynamically as needed. Each bit in the BitSet can either be true (set) or false (unset), making it an ideal choice for tasks such as manipulating sets of flags, managing collections of Boolean values, or performing operations on binary data.
Internally, BitSet uses a long array to store bits, which allows it to be memory efficient, especially compared to using an array of boolean primitives.
How BitSet Stores Bits Internally
BitSet Stores Bits InternallyA
BitSetuses an array oflongvalues (long[]) to store the bits.Each
longin Java is 64 bits wide, meaning onelongcan store the state of 64 bits (trueorfalsevalues).If you need to store, say, 128 bits, a
BitSetwill use 2 longs (128 / 64 = 2).
How boolean[] Stores Values Internally
boolean[] Stores Values InternallyIn a
boolean[], each element represents one bit of information (trueorfalse), but due to memory alignment and storage constraints, Java does not store booleans as single bits.Instead, Java typically uses 1 byte (8 bits) to store each
booleanvalue in an array, because most hardware cannot directly address individual bits.So, a
boolean[]of size 128 will use 128 bytes (1 byte perboolean).
Features
Dynamic Sizing: The size of a
BitSetis not fixed and can grow automatically as bits are set or cleared.Memory Efficiency:
BitSetis much more memory efficient than aboolean[]array since it stores bits compactly using long integers.Bitwise Operations: It supports logical operations such as
AND,OR,XOR, andAND NOT.Index-Based Access: Bits can be accessed and manipulated using their zero-based index.
Stream and Lambda Support: Java 8 and later versions added support for streaming through
BitSetusing methods likestream().Automatic Growth: When setting a bit at an index that exceeds the current size, the
BitSetautomatically resizes to accommodate the new index.Default State: All bits in a
BitSetare initiallyfalse.Serialization: The
BitSetclass implementsSerializable, allowing it to be serialized and deserialized.
Declaration & Functions
Declaration
To use a BitSet, simply import it and create an instance:
Key Methods and Functions
Setting and Clearing Bits:
Getting Bit Values:
Checking State:
Logical Operations:
Stream Support (Java 8+):
Miscellaneous:
Usage
1. Flags and Binary Representations:
BitSetis often used to represent flags or enable/disable states in an application.
2. Efficient Membership Testing:
It can be used to represent sets and perform operations like intersection and union.
3. Data Compression:
To store large numbers of Boolean values in minimal memory.
4. Prime Number Generation (Sieve of Eratosthenes):
BitSetis used to efficiently implement algorithms for generating prime numbers.
5. Stream-Based Processing:
Using
BitSetin conjunction with streams for advanced data processing.
Last updated