Reputation: 171
When my text file contains this:
a b c b
My HashSet and TreeSet say there are 3 unique words.
When my text file contains this:
a b c a
My HashSet and TreeSet say there are 4 unique words.
Why?
public static int countUnique1A(WordStream words) {
HashSet<String> hashSetA = new HashSet<String>();
for (String i : words) {
hashSetA.add(i);
}
return hashSetA.size();
}
public static int countUnique1B(WordStream words) {
TreeSet<String> treeSetA = new TreeSet<String>();
for (String i : words) {
treeSetA.add(i);
}
return treeSetA.size();
}
Upvotes: 0
Views: 153
Reputation: 30819
I guess it may be due to spaces between the words. E.g. HashSet
may contain 'a' and 'a '. Can you try changing:
hashSetA.add(i);
to
hashSetA.add(i.trim());
We need to do the same for treeSetA
as well.
Upvotes: 6