Last active
August 29, 2015 14:01
-
-
Save kjaquier/5258acfed247cd496f7d to your computer and use it in GitHub Desktop.
Enum based and memory efficient flag set.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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