java - For 循环遍历表

标签 java for-loop

假设我创建了一个表

char[][] table = new char[5][5];

并且我想使用 for 循环 来迭代它以创建“空间”。

for (int i = 0; i < table.length; i++)
for (int j = 0; j < table[i].length; j++)
       table[i][j] = ' ';   

第二行table[i].length中的[i]是什么意思?为什么不能像第一行那样只是 table.length ?谢谢

最佳答案

您的声明:

char[][] table = new char[5][5];

相当于:

// declare array of size 5, each element is a reference to one-dimen char[] array
char[][] table = new char[5][]; 

// initialize elements of table array, i.e. each row
table[0] = new char[5];
table[1] = new char[5];
table[2] = new char[5];
table[3] = new char[5];
table[4] = new char[5];

注意:例如,您可以使用不同大小的数组初始化每个“行”

table[3] = new char[255];

table[1].length将为5,而table[3].length将为255。

[“rows”]数组的这些大小与“聚合”数组大小table.length无关,因此您必须使用此“行”数组的大小循环遍历每个“行”。

关于java - For 循环遍历表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898625/

相关文章:

batch-file - for/f forfiles 批处理中的空格不起作用

java - MySQL JDBC 返回 0 个结果

java - 无法在android中使用JSONArray解析json

java - 数百个 CLOSE_WAIT 连接正在耗尽我的线程池

java - Docker 风格的 Java 命令行解析器

Javascript - 检查经纬度坐标是否在边界内

javascript - cakephp javascript动态更新

Java for循环错误,第一项重复

python - 如何确保Python中的for循环中重复的字符被考虑在内

java - 无法启动 Activity ComponentInfo (LOGCAT)