奇怪的 Java 空指针异常

Weird Java Null Pointer Exception

为什么我得到 NullPointerException?我在 Board.setStartPosition 中实例化节点对象。然后我使用 b.getStartPosition() 从我的驱动程序中调用它。我已经简化了我的代码,只留下相关信息。

Driver.java

Static Board b;

public static void main(String[] args){
     b = new Board(3,3);
     b.setStartPosition(1, 1);
     b.createPath(b.getStartPosition());
}

Board.java

public class Board {
    private int length;
    private int width;
    private Node[][] board;
    private ArrayList<Node> openList;
    private ArrayList<Node> closedList;
    private Node startPosition;
    private Node endPosition;

    Board(int length, int width){
        board = new Node[length][width];

        Random rand = new Random();

        for(int row=0; row < board.length; row++){
            for(int col=0; col < board[row].length; col++){

                int randomNum = rand.nextInt(10);

                if(randomNum == 0){
                    board[row][col] = new Node('X',row,col);
                }
                else{
                    board[row][col] = new Node('O',row,col);
                }
            }
        }
    }

    public Node getStartPosition() {
        return this.startPosition;
    }

    public void setStartPosition(int x, int y) {
        board[x][y].setStatus('S');
        board[x][y].setParent(null);
        startPosition = new Node('S', x, y);
        startPosition.setG(0);
    }

    public void createPath(Node n){

        //Continue until we cant find a path or we exhaust our searches

        //THIS IS WHERE I GET A NULLPOINTER. IT SEEMS TO THINK THAT MY NODE
        //n is null, eventhough when i pass it, i pass it by getting the startposition node
        //Add startPosition to closed list
        closedList.add(n);

        //Add things around start square to openList if applicable
        addToOpenList(n);       
    }

}

您还没有实例化您的 openList & closedList。您刚刚声明了它们:

private ArrayList<Node> openList;
private ArrayList<Node> closedList;

因此当你这样做时

        closedList.add(n);

        //Add things around start square to openList if applicable
        addToOpenList(n);  

你会得到NullPointerException.

您可以按照声明中所述初始化您的列表:

 private ArrayList<Node> openList = new ArrayList<>();
 private ArrayList<Node> closedList = new ArrayList<>();

你好像从来没有设置过closedList。为什么您认为它不是 null

您从未初始化 closedListopenList。变化

private ArrayList<Node> openList;
private ArrayList<Node> closedList;

类似于

private ArrayList<Node> openList = new ArrayList<>();
private ArrayList<Node> closedList = new ArrayList<>();

,更好的是,我建议您编程到List接口。真的很像,

private List<Node> openList = new ArrayList<>();
private List<Node> closedList = new ArrayList<>();