为什么我的数组被覆盖java

Sno*_*zip 3 java arrays encapsulation arraylist

我还在学习封装.我有一个GrammarList,每个Grammaremcapsulated有一个阵列listRule与他们所有的setter和getters.如下所示:

public class Grammar {

private enum Type {Left, Right, NULL};
private String Nom;
private static Type type = null;
private static ArrayList<Rule> listRule;

public Grammar(String nom, Type type) {
    this.Nom = nom;
    this.type = type;
    this.listRule = new ArrayList<Rule>();
}
...
}
Run Code Online (Sandbox Code Playgroud)

现在在我的程序中,我注意到每次添加新语法时都会覆盖我的数组listRule(添加了与语法相关的规则).我已经能够识别错误发生在Grammar grammar = new Grammar(parametre[0], null);清空所有其他语法的listRule内容的行上,因此listRule对于每个语法似乎都是相同的.我的数组listRule是否创建错误或是我的循环?

    try {
        while ((strLine = br.readLine()) != null) {
            String[] parametre = strLine.split(",");
            Grammar G = GrammarList.containsNom(parametre[0]);
            if (G == null) {
                Grammar grammar = new Grammar(parametre[0], null);
                grammarList.add(grammar);
                for (int i = 1; i < parametre.length; i++) {
                    SyntaxCheck check = new SyntaxCheck(parametre[i]);
                    if (check.isValid())
                        grammar.AddRule(check.Rule, check.Sens);
                }
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 6

您的listRule字段是static,这意味着每个实例共享同一个对象.

删除static关键字:

private ArrayList<Rule> listRule; // not static
Run Code Online (Sandbox Code Playgroud)