java 清除二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12945463/
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
Clear Two Dimensional Array
提问by Homer Homer
How can I clear a 6x6 "table", so that anything in it is cleared? (I made the clearbutton already with ActionListener...etc)
如何清除 6x6“表”,以便清除其中的任何内容?(我已经用 ActionListener 制作了 clearbutton ......等)
//other code above that creates window, below is the code that creates the table I need to clear
square = new JTextField[s][s];
for (int r=0; r!=s; r++) {
symbols[r] = new JTextField();
symbols[r].setBounds(35+r*35, 40, 30, 25);
win.add(symbols[r], 0);
for (int c=0; c!=s; c++) {
square[r][c] = new JTextField();
square[r][c].setBounds(15+c*35, 110+r*30, 30, 25);
win.add(square[r][c], 0);
}
}
win.repaint();
}
回答by Eric B.
Loop over the array and and set each element to null. You can use the java.utils.Arraysutility class to make things cleaner/neater.
循环遍历数组并将每个元素设置为 null。您可以使用java.utils.Arrays实用程序类使事情更干净/更整洁。
for( int i = 0; i < square.length; i++ )
Arrays.fill( square[i], null );
回答by Ivan Kovtun
Here is one line solution:
这是一行解决方案:
Arrays.stream(square).forEach(x -> Arrays.fill(x, null));
回答by MadProgrammer
Something like...
就像是...
for (int index = 0; index < square.length; index++) {
square[index] = null;
}
square = null;
Will do more then the trick (in fact the last line would normally be enough)...
会做更多的伎俩(实际上最后一行通常就足够了)......
If you're really paranoid...
如果你真的偏执...
for (int index = 0; index < square.length; index++) {
for (int inner = 0; inner < square[index].length; inner++) {
square[index][inner] = null;
}
square[index] = null;
}
square = null;