title: What are some alternatives to a bit array?
body: <p>I have an information retrieval application that creates bit arrays on the order of 10s of million bits. The number of "set" bits in the array varies widely, from all clear to all set. Currently, I'm using a straight-forward bit array (<code>java.util.BitSet</code>), so each of my bit arrays takes several megabytes.</p>
  
  <p>My plan is to look at the cardinality of the first <em>N</em> bits, then make a decision about what data structure to use for the remainder. Clearly some data structures are better for very sparse bit arrays, and others when roughly half the bits are set (when most bits are set, I can use negation to treat it as a sparse set of zeroes). </p>
  
  <ul>
  <li>What structures might be good at each extreme? </li>
  <li>Are there any in the middle?</li>
  </ul>
  
  <p>Here are a few constraints or hints:</p>
  
  <ol>
  <li>The bits are set only once, and in index order.</li>
  <li>I need 100% accuracy, so something like a Bloom filter isn't good enough.</li>
  <li>After the set is built, I need to be able to efficiently iterate over the "set" bits.</li>
  <li>The bits are randomly distributed, so run-length&ndash;encoding algorithms aren't likely to be much better than a simple list of bit indexes.</li>
  <li>I'm trying to optimize memory utilization, but speed still carries <em>some</em> weight.</li>
  </ol>
  
  <p>Something with an open source Java implementation is helpful, but not strictly necessary. I'm more interested in the fundamentals.</p>