BitSet Bit Flags Set Operations
Model permission flags as a BitSet and combine sets with and, or, andNot, then walk set bits with nextSetBit instead of looping over every index.
Code
import java.util.BitSet;
public class BitFlags {
public static void main(String[] args) {
String[] actions = {"read", "write", "delete", "export"};
BitSet flags = new BitSet();
flags.set(0); // read
flags.set(1); // write
BitSet requested = new BitSet();
requested.set(1); // write
requested.set(3); // export
// set operations:交集 and、并集 or、差集 andNot
BitSet common = (BitSet) flags.clone();
common.and(requested);
BitSet union = (BitSet) flags.clone();
union.or(requested);
BitSet missing = (BitSet) requested.clone();
missing.andNot(flags);
System.out.println("flags: " + flags);
System.out.println("common: " + common);
System.out.println("union size: " + union.cardinality());
for (int i = missing.nextSetBit(0); i >= 0; i = missing.nextSetBit(i + 1)) {
System.out.println("missing: " + actions[i]);
}
}
}What the code does
BitSet Bit Flags Set Operations keeps everything in the class BitFlags and the function main.
Repetition is confined to for (int i = missing.nextSetBit(0); i >= 0; i = missing.nextSetBit(i + 1)) — the rest of the file is straight-line.
Applying it
Look for the flags:, common:, union size: prefixes when the file runs; they tie each line to its step.
Statements that matter
String[] actions = {"read", "write", "delete", "export"};
BitSet missing = (BitSet) requested.clone();
BitSet common = (BitSet) flags.clone();
Interactive Tools for This Topic
FAQ
- What does BitSet Bit Flags Set Operations print when run?
- Running the file directly is enough — expect labeled output lines such as `flags:`, `common:`, `union size:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.