mtbc: maze I (white-red)
Mark T. B. Carroll ([personal profile] mtbc) wrote2019-05-17 07:36 am
Entry tags:

Arrays of Boolean values in Java

I have Java methods taking Boolean arguments and I want to test every combination of those. To have our testing framework try those combinations I need to provide it with a two-dimensional array of the n-bit Boolean values. The code I once had is,
final Boolean[][] testArguments = new Boolean[1 << argCount][];
int testNum = 0;
testArguments[testNum] = new Boolean[argCount];
Arrays.fill(testArguments[testNum], false);
while (++testNum < testArguments.length) {
  testArguments[testNum] = Arrays.copyOf(testArguments[testNum - 1], argCount);
  int argNum = argCount - 1;
  while (true) {
    if (testArguments[testNum][argNum]) {
      testArguments[testNum][argNum--] = false;
    } else {
      testArguments[testNum][argNum] = true;
      break;
    }
  }
}
return testArguments;
I thought that was quite neat. However, with advances in both Java and Google's Guava one can now replace all that with,
return Lists.cartesianProduct(Collections.nCopies(argCount, ImmutableList.of(false, true)))
       .stream().map(args -> args.stream().toArray(Boolean[]::new)).toArray(Boolean[][]::new);
Admittedly I doubt that either is easily read.

Post a comment in response:

This account has disabled anonymous posting.
(will be screened if not on Access List)
(will be screened if not on Access List)
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

If you are unable to use this captcha for any reason, please contact us by email at [email protected]