-1

I want to create a matrix with LinkedLists anf fill all the cells with 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 
        }
    }
}

What am I doing wrong?

MDBAN
  • 39
  • 1
  • 1
  • 4

1 Answers1

0

You are not creating any linked lists at all, and invoke methods on null instead. What did you expect to happen?

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);
    }
}

And what was T supposed to do? You are adding integer zeroes, this cannot work for anything except Integer.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93