4 min read
If you've ever assumed that Java's BitSet is just a glorified boolean array, you're not alone. I used to think the same-until I took a peek under the hood. What I found was pretty surprising, and if you're curious too, you're in for a treat. Let's dive into why BitSet is way cooler than it seems to be.
Java BitSet is much more than a simple boolean array. It uses bit manipulation on long data types to efficiently store and manage data. If this sounds confusing, don't worry—we'll break it down.
A long in Java is a 64-bit number, meaning it can store 64 individual bits. With bit manipulation, you can directly control each of these bits.
For example, to set a specific bit (let's say the 12th bit) in a long variable, you can use the OR operation. Imagine you have a 64-bit long variable called data, and you want to set the 12th bit to 1. You'd do something like this:
data | 0000000000010000000000000000000000000000000000000000000000000000L
Here, everything is 0 except the bit you want to set. As a result, only that bit gets updated, while the rest remains unchanged.
Now, if you want to check the value of the 12th bit in this variable, you'd use the AND operation:
data & 0000000000010000000000000000000000000000000000000000000000000000L
This will return 0 or 1, depending on whether that bit is set or not.
Bitset stores all the data in a long array. This continuously keeps changing based on the data needs of the client just like most collections in Java.
If you want to store the 1,000th bit, you first find the right index in the array. Then, you determine which specific bit (out of the 64 in that long) represents the 1,000th bit. Once you've identified it, you perform the necessary bitwise operation on that bit.
When something is required to be set in the Bitset, a set() method is invoked. This method first finds out the index of the array this bit will fall into. Then, it verifies if the array has the required capacity to store it. After that, it simply sets the bit using an OR operation that we saw above.
get() operation works in a similar way. We first find out the index of the array this bit will fall into. Then, we ensure that this position is in a valid range or not. If it is, then we use an AND operation to extract the bit value.
BitSet offers many additional features, but to keep this article focused, we won't dive into all of them here. If you're curious, I encourage you to explore its full capabilities by checking out the source code—it's a fascinating read!
Java BitSet is way more than just a fancy boolean array—it's a clever, efficient tool that makes managing bits surprisingly cool. Hopefully, this gave you a glimpse of how it works under the hood and why it's worth exploring.
Hope you learned something new today.
Thank you for reading. Happy coding!