简体   繁体   中英

Having trouble with adding an ArrayList to an ArrayList of ArrayLists

public class Tabel {
    private static int dimension;

    private ArrayList<ArrayList<Character>> tabel;


    public Tabel(int dimension) {

        Tabel.dimension = dimension;

        for (int i=0;i<Tabel.dimension*Tabel.dimension;i++) {
           tabel.add(new ArrayList<Character>());
        }

     }
}

When I try to debug (eclipse ide) I get a lot of weird "errors" or at the very least I encounter something I consider unexpected.

The private static int does not appear in the "variables" section of debug.

I get a NullPointerException on tabel.add(...) but when I watch the debug, it enters the for once, does not add anything in the table because when I hit "next" instead of jumping to the closing braces it jumps out of the function.

If I comment the .add it works so that's the problem (I think). Is my syntax wrong ? or should I post more code ?

tabel is not initialized, so it is null.

Change

private ArrayList<ArrayList<Character>> tabel;

to

private ArrayList<ArrayList<Character>> tabel = new ArrayList<ArrayList<Character>>();

Or better:

private List<ArrayList<Character>> tabel = new ArrayList<ArrayList<Character>>();

since this does not tie tabel to ArrayList .

You have not initialized the private List. Do the following:

private List<ArrayList<Character>> tabel = new ArrayList<ArrayList<Character>>();

I'd have trouble understanding that level of nesting too.

It's better to refer to List rather than ArrayList. Unless you need a method in the concrete class, it makes your program more flexible to refer to the interface and the methods in the interface.

Create a class (1) that has a field defined as a List of Character. Set the field to a new ArrayList in the constructor.

Create another class (2) that has a field defined as a List of class (1). Set the field to a new ArrayList in the constructor.

Create another class (3) that has a field defined as a List of class (2). Set the field to a new ArrayList in the constructor.

Since you understand what you're doing, you can give these 3 classes more meaningful names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM