In Java, I have an array of a million or so flags true/false to store in mind. Should BitSet help? Although it implements a Set, will it be possible to iterate its elements as fast as if it would be an array boolean[]?
Sorry if the question has been asked. First I tried to split an array into chunks of binary represented ints and form int[] as a result of those binaries, so I could reduce the size by 32, but this is quite low-level.
I found some critics of the BitSet elsewhere and that boolean[] stores a lot of extra memory => bad for large arrays.
Any better idea to store a million of flags?
You can have billions of bits in a BitSet.
A boolean[] uses one byte per bit (on most JVMs) whereas BitSet uses one bit per bit. For small arrays, a boolean[] is faster, but when you are testing the size of your CPU cache a BitSet can be more efficient.
BTW: Using a BitSet is slightly slower for small sizes because it need to extract out a bit out of each a word of memory. A
byte[]has the same issue, so if you want to set bit yourself, I suggest you use aint[]like BitSet does.An example using BitSet
prints