views:

756

answers:

6

Is there anything I can cast a boolean array to in Java? It would be nice if I could say

boolean[] bools = new boolean[8];
int j = (int)bools;

But I'm not sure if that's feasible in Java.

+1  A: 

That syntax is not legal in Java.

What is it you are after? If you are looking for the length, you can do this:

int j = bools.length;
akf
I think he wants something like: 00000111 ( or false, false, false, false, false, true, true, true ) and have it as 7.
OscarRyz
+3  A: 

No, you can't do this with a boolean[] - but it sounds like you might want a BitSet which is a compact representation of a set of Boolean values.

Jon Skeet
+3  A: 

If you want a bit pattern, I think you're better off using bitmasks e.g.

final int BIT_1 = 0x00000001;
final int BIT_2 = 0x00000002;

// represents a bit mask
int value;

// enable bit 2
value |= BIT_2

// switch off bit 1
value &= ~BIT_1

// do something if bit 1 is set...
if (value & BIT_1) {

etc. See here for more examples.

Brian Agnew
Could you add more detail on the etc part?
OscarRyz
+2  A: 

the size of Java booleans is implementation specific, and it's probably not a single bit in any case. if you want an easy way to manipulate bits, take a look at BitSet.

Omry
They are not only implementation specific, but almost always full "int" size (or, more accurately, machine word size). To not do it this way would slow down your system.
Bill K
A: 

You can cast boolean[] to Object, but that's about it.

mobrule
+1  A: 

Here's one quick-and-dirty way to convert from a boolean[] to an integer:

static int intFromBooleanArray(boolean[] array) {
    return new BigInteger(Arrays.toString(array)
                          .replace("true", "1")
                          .replace("false", "0")
                          .replaceAll("[^01]", ""), 2).intValue();
}

example:

intFromBooleanArray(new boolean[] {true, false, true, false, true, false});
// => 42.
finnw
+1 nice .......
OscarRyz