为什么我的数组被覆盖 java
Why is my array being overwritten java
我还在学习封装。我有一个 GrammarList
,其中每个封装的 Grammar
都有一个数组 listRule
及其所有设置器和获取器。如此处所示:
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();
}
您的 listRule
字段是 static
,这意味着每个实例共享同一个对象。
删除 static
关键字:
private ArrayList<Rule> listRule; // not static
我还在学习封装。我有一个 GrammarList
,其中每个封装的 Grammar
都有一个数组 listRule
及其所有设置器和获取器。如此处所示:
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();
}
您的 listRule
字段是 static
,这意味着每个实例共享同一个对象。
删除 static
关键字:
private ArrayList<Rule> listRule; // not static