Aditya Chawla
Aditya Chawla

Reputation: 107

Getting NullPointerException while adding element to ArrayList

My code:

import java.util.Random;
import java.util.ArrayList;

public class Percolation {
    ArrayList<int[]> grid;
    Random dice = new Random();
    public Percolation(int n){
        for(int i=0;i<n;i++){
            grid.add(new int[n]);
        }
        output(grid,n);
    }

    public void output(ArrayList<int[]> x,int n){
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                System.out.println(x.get(i)[j]);
    }
    public static void main(String[] args){
        Percolation p = new Percolation(2);
    }
}

Using this code throws a NullPointerException at grid.add(new int[n]). How can I add data to grid?

Upvotes: 1

Views: 211

Answers (3)

Sunil Kanzar
Sunil Kanzar

Reputation: 1260

Without initialization you can not add element in list.

And you can also pass another ArrayList in <> e.g.:

ArrayList<ArrayList> grid = new ArrayList<>();

Because it is much dynamic.

Upvotes: 0

Abi
Abi

Reputation: 734

import java.util.Random;
import java.util.ArrayList;

public class Percolation {
 ArrayList<int[]> grid = new ArrayList<>(); // Initialize the array List here before using
 Random dice = new Random();
 public Percolation(int n){
    for(int i=0;i<n;i++){
        grid.add(new int[n]);
    }
    output(grid,n);
}

public void output(ArrayList<int[]> x,int n){
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            System.out.println(x.get(i)[j]);
}
public static void main(String[] args){
    Percolation p = new Percolation(2);
 }
}

Upvotes: 0

stinepike
stinepike

Reputation: 54672

You haven't initialize the ArrayList.

ArrayList<int[]> grid = new ArrayList<>();

Upvotes: 3

Related Questions