【问题标题】:2d-LinkedList java.lang.NullPointerException by filling the 2d-LinkedList [duplicate]2d-LinkedList java.lang.NullPointerException 通过填充 2d-LinkedList [重复]
【发布时间】:2018-01-21 16:21:37
【问题描述】:

我想用 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 
        }
    }
}

我做错了什么?

【问题讨论】:

  • data 来自哪里?
  • 修复了它。应该是matrix
  • matrix.get(i)null,改变这个事实。
  • @AniketSahrawat 如果 OP 这样做,整个 for 循环将不会做任何事情。
  • @luk2302 我不明白,什么意思?

标签: java class constructor nullpointerexception


【解决方案1】:

您根本没有创建任何链接列表,而是调用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 之外的任何东西都不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 2016-12-23
    相关资源
    最近更新 更多