Java 将布尔数组中的所有值设置为 true
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20870353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting all values in a boolean array to true
提问by Fraser Price
Is there a method in Java for setting all values in a boolean array to true?
Java 中是否有将布尔数组中的所有值设置为 true 的方法?
Obviously I could do this with a for loop, but if I have (for example) a large 3D array, I imagine using a loop would be quite inefficient.
显然我可以用 for 循环来做到这一点,但如果我有(例如)一个大型 3D 数组,我想使用循环会非常低效。
Is there any method in Java to set all values in a certain array to true, or alternatively to set all values to true when the array is initialised?
Java中是否有任何方法可以将某个数组中的所有值设置为true,或者在初始化数组时将所有值设置为true?
(e.g
(例如
boolean[][][] newBool = new boolean[100][100][100];
newBool.setAllTrue();
//Rather than
for(int a = 0; a < 100; a++) {
for(int b = 0; b < 100; b++) {
for(int c = 0; c < 100; c++) {
newBool[a][b][c] = true;
}
}
}
采纳答案by Hyman
You could use Java 7's Arrays.fill which assigns a specified value to every element of the specified array...so something like. This is still using a loop but at least is shorter to write.
您可以使用 Java 7 的 Arrays.fill,它为指定数组的每个元素分配一个指定的值...... 这仍然使用循环,但至少写起来更短。
boolean[] toFill = new boolean[100] {};
Arrays.fill(toFill, true);
回答by stinepike
There is no shortcut in this situation. and the best option is using a for loop. there might be several other options, like setting the value while declaring (!!). Or you can use Arrays.fill methods but internally it will use loop. or if possible then toggle the use of your values.
在这种情况下没有捷径可走。最好的选择是使用 for 循环。可能还有其他几个选项,例如在声明 (!!) 时设置值。或者您可以使用 Arrays.fill 方法,但在内部它将使用循环。或者如果可能,然后切换您的价值观的使用。
回答by Kirill Solokhov
It's much better to use java.util.BitSet instead of array of booleans. In a BitSet you can set values in some range. It's memory effective because it uses array of longs for internal state.
使用 java.util.BitSet 而不是布尔数组要好得多。在 BitSet 中,您可以在某个范围内设置值。它是内存有效的,因为它使用 long 数组作为内部状态。
BitSet bSet = new BitSet(10);
bSet.set(0,10);