2017-10-18 118 views
3

我仍然在学习封装。我有一个GrammarList,其中每个Grammar emcapsulated有一个阵列listRule与他们的所有setter &获得者。因为在这里看到:为什么我的数组被覆盖java

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

现在在我的节目,我发现我的阵列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(); 
    } 
+0

欢迎堆栈溢出,为更好地帮助越早发布适当[MCVE] – Frakcool

回答

6

listRulestatic,这意味着每个实例共享同一个对象。

删除static关键字:

private ArrayList<Rule> listRule; // not static