This is definitely simpler, and I think may be faster, because it only accesses those elements of b
whose index is in a
. It does not scan the whole of b
looking for the next set bit.
public static int[] intersect(BitSet b, int[] a){
int[] rawResult = new int[a.length];
int c = 0;
for(int i : a){
if(b.get(i)){
rawResult[c] = i;
c++;
}
}
int[] result = new int[c];
System.arraycopy(rawResult, 0, result, 0, c);
return result;
}