Skip to content

Instantly share code, notes, and snippets.

@kjaquier
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjaquier/5258acfed247cd496f7d to your computer and use it in GitHub Desktop.
Save kjaquier/5258acfed247cd496f7d to your computer and use it in GitHub Desktop.
Enum based and memory efficient flag set.
public class BitSet<T extends Enum<?>> {
private byte[] bytes;
@SafeVarargs
public BitSet(T... elements) {
bytes = new byte[elements.length / 8 + 1];
}
private int bitMask(int ordinal) {
return 1 << (ordinal % 8);
}
public boolean get(T flag) {
return (bytes[flag.ordinal() / 8] & bitMask(flag.ordinal())) != 0;
}
public void set(T flag, boolean value) {
if (value)
bytes[flag.ordinal() / 8] |= bitMask(flag.ordinal());
else
bytes[flag.ordinal() / 8] &= ~bitMask(flag.ordinal());
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = bytes.length - 1; i >= 0; i--) {
for (int j = 7; j >= 0; j--) {
sb.append((bytes[i] & bitMask(j)) != 0 ? 1 : 0);
}
}
sb.append("]");
return sb.toString();
}
private static enum Caracteristics {
IsBig, IsHeavy, IsHuman, IsDangerous, IsBeautiful, IsVisible, IsSolid, IsSmart, IsNatural;
}
public static void main(String[] args) {
BitSet<Caracteristics> bs = new BitSet<>(Caracteristics.values());
bs.set(Caracteristics.IsBig, true);
bs.set(Caracteristics.IsHeavy, false);
bs.set(Caracteristics.IsDangerous, true);
bs.set(Caracteristics.IsSmart, true);
bs.set(Caracteristics.IsNatural, true);
System.out.println(bs.get(Caracteristics.IsBig));
System.out.println(bs.get(Caracteristics.IsHeavy));
System.out.println(bs.get(Caracteristics.IsDangerous));
System.out.println(bs.get(Caracteristics.IsSmart));
System.out.println(bs.get(Caracteristics.IsNatural));
System.out.println(bs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment