I need to randomly generate an array of 8 true and false values, with exactly 4 of the values being true.
This is a variation of a card shuffling problem
List<Boolean> flags = new ArrayList<Boolean>();
for(int i = 0; i < 4; i++) flags.add(true);
for(int i = 0; i < 4; i++) flags.add(false);
Collections.shuffle(flags);
This completes in O(N) time and you can be sure you have the number of true/false you wanted.
Note: all solutions have an equal chance of occurring. The problem with just changing the values until you get the total you want is it is hard to ensure you don't have a bias in the results you produce.
From the JavaDoc for Collections.shuffle(List)
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.
This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.
This method runs in linear time. If the specified list does not implement the RandomAccess interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a "sequential access" list in place.