Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My algorithm use a huge array of boolean, and as I was taught, it take 1 byte for each boolean variable. Is there anyway to declare a boolean array and reduce the memory usage, because I'm working on phone environment.

EDIT: My friend and I are discussing if BitSet is slower than normal Boolean array. Please clarify this. The algorithm still needs performance as best demand.

like image 937
Luke Vo Avatar asked Jan 13 '12 05:01

Luke Vo


People also ask

How is a bit defined in Java?

A bit is a basic unit of information or is the smallest unit of data in the computer and digital communications, which stands for binary digit.


2 Answers

BitSet

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.

Link to benchmark between using boolean versus BitSet

like image 70
Aravind Yarram Avatar answered Sep 21 '22 01:09

Aravind Yarram


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

A specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.

e.g.

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 its appropriate.

like image 44
Peter Lawrey Avatar answered Sep 21 '22 01:09

Peter Lawrey