You need to understand variable shadowing.
Begin with a simple example, not using a constructor:
static int test = 10;
public static void main(final String[] args) throws IOException {
int test = 20;
System.out.println(test);
}
What does this code print?
The answer is 20
. The reason is that the test
you declare in the method is actually a different test
to the one you declare in the class. You have two variables in different scopes.
You have the same issue here:
public class NgramModel {
//one `ngram`
private HashMap<String,Integer> ngram;
public NgramModel() {
//a second `ngram`
HashMap<String,Integer> ngram = new HashMap <String, Integer>();
ngram.put("aa", 2);
}
}
You do not need to redeclare the variable:
public class NgramModel {
//one `ngram`
private HashMap<String,Integer> ngram;
public NgramModel() {
//reference the `ngram` from above
ngram = new HashMap <String, Integer>();
ngram.put("aa", 2);
}
}