Arrays of Boolean values in Java
May. 17th, 2019 07:36 am![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
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,
I thought that was quite neat. However, with advances in both Java and Google's Guava one can now replace all that with,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;
Admittedly I doubt that either is easily read.return Lists.cartesianProduct(Collections.nCopies(argCount, ImmutableList.of(false, true))) .stream().map(args -> args.stream().toArray(Boolean[]::new)).toArray(Boolean[][]::new);