java - 无法在类中创建属性
问题描述
我已经定义了一个名为 Cell 的类,如果我调用构造函数,我会得到一个溢出执行。为什么我不能在构造函数中调用 buildallneigbors() ?
import java.util.ArrayList;
import java.util.List;
import java.lang.Exception;
public final class Cell {
private int row;
private int column;
public Cell neigborcell[];
public List<Border> borderlist;
private int hashwert;
public Cell(int row, int column) {
this.row = row;
this.column = column;
Cell neigborcell[] = new Cell[4];
List<Border> borderlist = new ArrayList<Border>();
buildallneigbors();
}
public void buildallneigbors(){
this.neigborcell[0] = new Cell(row - 1, column);
this.neigborcell[1] = new Cell(row, column + 1);
this.neigborcell[2] = new Cell(row + 1, column);
this.neigborcell[3] = new Cell(row, column - 1);
}
解决方案
为了填充neighborCell[]
您需要已经实例化其他单元格。因此,从本质上讲,它需要进行两次操作。一个用于创建单元格,另一个用于填充邻居:
public class CellBuilder {
public static void main(String[] args) {
List<Cell> cells = IntStream.range(0, 6)
.mapToObj(row -> IntStream.range(0, 7).mapToObj(column -> new Cell(row, column)))
.flatMap(cell -> cell)
.collect(Collectors.toList());
cells.forEach(cell -> cell.buildAllNeigbors(cells));
}
public static final class Cell {
private int row;
private int column;
public Cell neighbourCell[] = new Cell[4];
public Cell(int row, int column) {
this.row = row;
this.column = column;
}
public void buildAllNeigbors(Collection<Cell> allCells) {
this.neighbourCell[0] = locateCell(allCells, row - 1, column);
this.neighbourCell[1] = locateCell(allCells, row, column + 1);
this.neighbourCell[2] = locateCell(allCells, row + 1, column);
this.neighbourCell[3] = locateCell(allCells, row, column - 1);
}
private Cell locateCell(Collection<Cell> cells, int rowToFind, int columnToFind) {
return cells.stream().filter(cell -> cell.row == rowToFind).filter(cell -> cell.column == columnToFind).findAny().orElse(null);
}
}
}
推荐阅读
- websocket - Vertx websocket 在一个新的verticle中
- apache-flink - 为什么 Flink 中没有计时器指标来记录 Operator 中特定方法的处理时间。[Apache Flink - 1.12.2]
- reactjs - react中的click函数甚至多次调用并且索引文件中没有使用严格模式
- .net - Identity .net core 3.1 如何使用持久 cookie
- python - 使用 Python 在 SQL 中为复杂的 json 数据自动创建表
- r - 想要创建一个带有 2 个条形图的条形图 x 对 R 中的所有数值进行分组
- swift - Alamofire 上传失败,文件超过 1MB
- spring - Spring - 获取加载了惰性元素的实体页面
- r - Reorder certain columns by a pattern within a data.table R
- tensorflow - 如何在张量流中导入 ReductionV2?