Is it possible to declare a 1-bit variable in Java?

My algorithm uses a huge boolean array, and as I was taught, it takes 1 byte for each boolean variable. Do I need to declare a Boolean array at all and reduce memory usage, because I work in a phone environment.

EDIT: My friend and I are discussing whether BitSet is slower than a regular Boolean array. Please clarify this. The algorithm still needs performance at its best.

+6
source share
2 answers

Bitset

This class implements a bit vector that grows as needed. each bit set component has a logical value. BitSet bits - This is indexed by non-negative integers. Individual indexed bits may be checked, set, or cleared. One BitSet can be used to modify the contents of another BitSet through logical AND, logical inclusion of OR, and logical operations of exclusive OR.

Link to test between using boolean versus BitSet

+18
source

You can use EnumSet . This allows you to use named bits and may be friendlier than using BitSet, which uses indexed bits.

A specialized implementation of Set for use with enumeration types. All elements in an enumeration set must come from the same enumeration type, which is specified, explicitly or implicitly, when creating the set. Enum sets are represented internally as bit vectors. This view is extremely compact and efficient. The space and running time of this class should be good enough to allow it to be used as a high-quality, typical alternative to traditional int-based "bit flags". Even bulk operations (such as containsAll and retainAll) must be performed very quickly if their argument is also an enumeration.

eg.

 BitSet bs = new BitSet(4); bs.set(1); // READY bs.set(3); // LARGE_FLAG boolean largeFlag = bs.get(1); // LARGE_FLAG System.out.println("Using BitSet: "+bs); EnumSet<Settings> settings = EnumSet.noneOf(Settings.class); settings.add(Settings.READY); settings.add(Settings.LARGE_FLAG); boolean largeFlag2 = settings.contains(Settings.LARGE_FLAG); System.out.println("Using EnumSet: "+settings); 

prints

 Using BitSet: {1, 3} Using EnumSet: [READY, LARGE_FLAG] 

IMHO EnumSet is much clearer if necessary.

+1
source

Source: https://habr.com/ru/post/905883/


All Articles