When looking at the structure of counts
and words
in a debugger just before the print statement, it becomes clear that there is something amiss.
words: counts 0 = this 0 = 3 1 = is 1 = 3 2 = a 2 = 2 3 = test 3 = 3 4 = also 4 = 2 5 = the 5 = 2 6 = last 6 = 2 7 = 1 8 = 0 9 = 1 10 = 1 11 = 1 12 = 1 13 = 1 14 = 1
The problem is the add statement in the ArrayList. From the Javadocs:
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
And so, each time you are doing that counts.add(q, counts.get(q) + 1)
you are inserting another element into the list. You should instead use set
.
Setting a breakpoint on the for
and running this through a debugger (eclipse debugging tutorial) I can look at the arrays as each one of them grows:
words: counts 0 = this 0 = 0
This is from the first bit of:
words.add(wordList[0]);
counts.add(0);
When it hits the for loop again:
words: counts 0 = this 0 = 1 1 = 0
What happened there is that the counts.add(0,1)
put a 1 at the 0th location and then shifted everything else in the array down.
After several iterations of the not finding, we are back to this again.
words: counts 0 = this 0 = 1 1 = is 1 = 0 2 = a 2 = 1 3 = test 3 = 1 4 = 1
And then matching the 'this' again:
words: counts 0 = this 0 = 2 1 = is 1 = 1 2 = a 2 = 0 3 = test 3 = 1 4 = 1 5 = 1
And you should be able to see how this structure is growing incorrectly.