获取数组中单元格所有邻居时避免数组越界异常求助
问题分析与修复方案
错误根源:你的边界判断逻辑完全错误。第二个
if里的c <= (col + 1) && r <= (row + 1)根本不是在检查是否超出网格边界,而是在判断是否不超过当前单元格的右下邻位。比如处理最后一行(索引row=2)时,row+1=3,但你的网格只有3行(索引范围0-2),这时候r<=3会允许r=3,直接触发数组越界。正确的边界判断逻辑:应该用网格的实际尺寸来限制索引范围:
- 行索引
r必须满足0 <= r < landscape.length(landscape.length是网格总行数) - 列索引
c必须满足0 <= c < landscape[r].length(假设所有行的列数一致,也可以提前定义变量存储总列数)
- 行索引
修正后的完整代码:
public ArrayList<Cell> getNeighbors(int row, int col) { ArrayList<Cell> neighbors = new ArrayList<Cell>(); int totalRows = landscape.length; int totalCols = landscape[0].length; // 假设所有行列数相同,若不同需单独处理每行 for (int r = row - 1; r <= row + 1; r++) { for (int c = col - 1; c <= col + 1; c++) { // 跳过当前单元格本身 if (r == row && c == col) { continue; } // 检查索引是否在网格有效范围内 if (r >= 0 && r < totalRows && c >= 0 && c < totalCols) { neighbors.add(landscape[r][c]); } } } return neighbors; }
- 额外优化说明:
- 提前存储总行数和总列数,避免循环中重复调用
landscape.length,提升代码效率。 - 将
!(r == row && c == col)改为if (r == row && c == col) continue;,逻辑更直观,可读性更强。
- 提前存储总行数和总列数,避免循环中重复调用
内容的提问来源于stack exchange,提问作者displayName
相关产品推荐
相关产品推荐

