Ok, I’m stumped by this one I have no idea what’s causing this problem. The problem I am having occurs in a class that when given a text file, will find the number of instances of one letter coming after another. So I have a HashMapCharacter, HashMap that stores all of this. The keys of the hash are all the characters contained in the text, and each of these characters corresponds to an inner Hash containing the number of cases of a character(inner hash key) after the outerhash key. The inner hash with key ‘a’ would contain the number of times ‘b’ comes after ‘a’, the number of times ‘c’ comes after ‘a’, the number of times ‘z’ comes after ‘a’, so on and so forth for all the characters that come after ‘a’. MuteableInt just holds an int value, and allows it to be incremented by method.
The error occurs when I compute the total of all the counts contained in each inner Hash. I find the total, and then I insert it under the key ‘~’. The total is correct when I insert it, but when I pull out the total later, I find that for every inner Hash the total takes on the value of the last total I entered.
currHash.put('~', total);
So, when analyzing War and Peace the last total entered is that of ‘x’, which has a total count of 3987. When I pull out the total instance count of ‘h’, or any other character, it is also 3987. Hopefully this makes sense, here is the offending code.
public class CountTransitions {
HashMap<Character, HashMap<Character, MuteableInt>> counts;
public void calcTotal() {
Iterator<Character> iterator = counts.keySet().iterator();
HashMap<Character, MuteableInt> currHash;
char curr, next;
MuteableInt total = new MuteableInt(0);
MuteableInt count = new MuteableInt(0);
while (iterator.hasNext()) {
curr = iterator.next();
currHash = counts.get(curr);
total.set(0);
Iterator<Character> innerIt = currHash.keySet().iterator();
while (innerIt.hasNext()) {
next = innerIt.next();
count = currHash.get(next);
total.add(count);
}//end while
System.out.println("Total: " + total);
currHash.put('~', total);
}//end while
}
}//end class
You only ever create one
MuteableIntfortotal, and put this same object reference into each sub-HashMap. This is why they’re changing — it’s one counter you’re incrementing everywhere, not many.