填充2d-LinkedList的2d-LinkedList java.lang.NullPointerException

时间:2018-01-21 16:21:37

标签: java class constructor nullpointerexception

我想用LinkedLists创建一个矩阵,并用0填充所有单元格。

private LinkedList<LinkedList<T>> matrix;
private int rows;
private int columns;


// constructor
public Matrix(int rows, int columns){
    this.rows = rows;
    this.columns = columns;
    for(int i=0; i<rows; i++){
        for(int j=0; j<columns; j++){ 
            matrix.get(i).add(0);  // here I get the NullPointerException 
        }
    }
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您根本不创建任何链接列表,而是调用null上的方法。你期望发生什么?

private LinkedList<LinkedList<Integer>> matrix;
private int rows;
private int columns;

// constructor
public Matrix(int rows, int columns){
    this.rows = rows;
    this.columns = columns;
    this.matrix = new LinkedList<LinkedList<Integer>>();
    for(int i=0; i<rows; i++){
        LinkedList<Integer> row = new LinkedList<>();
        for(int j=0; j<columns; j++){ 
            row.add((Integer)0);
        }
        matrix.add(row);
    }
}

T应该做什么?您正在添加整数零,这对除Integer之外的任何内容都不起作用。

相关问题