HashMap storing duplicates ?

Hi,

this is really strange . I did a program using hashmap to store word and frequencies and what i got as output if the line cat cat mouse
is this

{ cat , cat , mouse=1}

The part of the program is below. I cant seem to find the bug.  Could anyone pls look at it ? I always thought that map does not allow duplicates..but

public static void main(String []args)
{
Scanner reader;
StringTokenizer tokens;
String[] wordList;
HashMap<String,Integer> hm=new HashMap<String,Integer>();
Collections c;

if(args.length!=1)
System.err.println("Incorrect number of arguments passed..Exiting..");

else{

try{
reader=new Scanner(new File(args[0]));
while(reader.hasNextLine())

try{
reader=new Scanner(new File(args[0]));
while(reader.hasNextLine())
{
wordList=reader.nextLine().split(",.\n");

for(String word:wordList)
{
if(hm.get(word)!=null)
{
Integer value=hm.get(word);
value=value+1;
hm.put(word,value);
}
else
{
Integer value=1;
hm.put(word,value);
}
}

zizi21Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Ajay-SinghConnect With a Mentor Commented:
change this
 
for(String word:wordList)
{
if(hm.get(word)!=null)

 
to
 
for(String word:wordList)
{
word = word.trim();
if(hm.get(word)!=null)
0
 
modsiwCommented:
please post the contents of the file you are reading in.

please post the result of
System.out.println(hm);
after your for loop.
0
 
modsiwCommented:
also, note that
"cat" and "cat " are not equal
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
mnrzCommented:
definitely the first cat and second cat are different somehow, for example an space before or after the word "cat" => " cat"
0
 
CEHJCommented:
Try changing the split line to

wordList=reader.nextLine().split("\\s*,\\s*");
0
 
CEHJCommented:
Actually forget that - Ajay's approach is better
0
 
zizi21Author Commented:
sorry..just finished two other exams..going back to java..forgive me for the late reply...
0
All Courses

From novice to tech pro — start learning today.