简体   繁体   English

在将ArrayList添加到ArrayList的ArrayList时遇到麻烦

[英]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. 当我尝试调试(eclipse ide)时,我遇到很多奇怪的“错误”,或者至少遇到了一些我认为是意外的事情。

The private static int does not appear in the "variables" section of debug. 专用静态int不会出现在调试的“变量”部分中。

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. 我得到一个NullPointerExceptiontabel.add(...)但是当我观看了调试,它进入for一次,没有在表中添加任何东西,因为当我点击“下一步”,而不是跳转到花括号它跳出功能的

If I comment the .add it works so that's the problem (I think). 如果我对.add注释, .add它将起作用(我认为)。 Is my syntax wrong ? 我的语法错误吗? or should I post more code ? 还是我应该发布更多代码?

tabel is not initialized, so it is null. tabel未初始化,因此为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 . 因为这不会将tabelArrayList绑定tabel

You have not initialized the private List. 您尚未初始化private列表。 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. 最好引用List而不是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. 创建具有定义为“字符列表”的字段的类(1)。 Set the field to a new ArrayList in the constructor. 将字段设置为构造函数中的新ArrayList。

Create another class (2) that has a field defined as a List of class (1). 创建另一个类(2),该类的字段定义为类(1)的列表。 Set the field to a new ArrayList in the constructor. 将字段设置为构造函数中的新ArrayList。

Create another class (3) that has a field defined as a List of class (2). 创建另一个具有定义为类列表(2)的字段的类(3)。 Set the field to a new ArrayList in the constructor. 将字段设置为构造函数中的新ArrayList。

Since you understand what you're doing, you can give these 3 classes more meaningful names. 由于您了解自己在做什么,因此可以为这3个类指定更有意义的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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