java 我想将布尔数组中的所有值设置为 false 而不重新初始化它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10492409/
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
I'd like to set all the values in a boolean array to false without re-initializing it
提问by EnkeiRC5
public boolean used[] = new boolean[26];
Here is what I have, and it's working great. I know they are all going to be set as false by default. But, as my application is used for a while, some of those are changed to "true". (Which is fine, since that's what my code is supposed to do).
这是我所拥有的,而且效果很好。我知道默认情况下它们都将被设置为 false。但是,由于我的应用程序使用了一段时间,其中一些更改为“true”。(这很好,因为这是我的代码应该做的)。
I'm trying to create a "reset" button, which will simulate a reset-like action. Where all variables are restored to what they were when the window was initially created (all drawings go away - just a fresh restart).
我正在尝试创建一个“重置”按钮,它将模拟类似重置的操作。所有变量都恢复到最初创建窗口时的状态(所有图形都消失了 - 只是重新启动)。
And I need all of those true booleans to go back to false in one fell swoop. Any ideas?
我需要所有这些真正的布尔值一举回到 false。有任何想法吗?
回答by Chris Pitman
回答by EnkeiRC5
Arrays.filluses a rangecheckbefore filling your array.
Arrays.fill在填充数组之前使用范围检查。
public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {
rangeCheck(a.length, fromIndex, toIndex);
for (int i=fromIndex; i<toIndex; i++)
a[i] = val;
}
/**
* Check that fromIndex and toIndex are in range, and throw an
* appropriate exception if they aren't.
*/
private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex+")");
if (fromIndex < 0)
throw new ArrayIndexOutOfBoundsException(fromIndex);
if (toIndex > arrayLen)
throw new ArrayIndexOutOfBoundsException(toIndex);
}
if you don't need rangeCheck, you can just use a forloopto fill up your boolean array.
如果您不需要 rangeCheck,您可以使用forloop来填充您的布尔数组。
for(int i = 0; i < used.length; ++i){
used[i] = false;
}
回答by miks
You can just recreate your array, it will be initialized by default to false.
您可以重新创建数组,默认情况下它会被初始化为 false。
That is when you implement the reset yo can do
那就是当你实施重置你可以做的
used[] = new boolean[26];
回答by Ernest Friedman-Hill
Use java.util.Arrays.fill()
:
使用java.util.Arrays.fill()
:
Arrays.fill(used, false);