首页 > 解决方案 > 无法在类中创建属性

问题描述

我已经定义了一个名为 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);
        }

标签: java

解决方案


为了填充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);
        }
    }
}

推荐阅读