2017-10-18 73 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