Link to home
Start Free TrialLog in
Avatar of zizi21
zizi21

asked on

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);
}
}

Avatar of modsiw
modsiw

please post the contents of the file you are reading in.

please post the result of
System.out.println(hm);
after your for loop.
also, note that
"cat" and "cat " are not equal
ASKER CERTIFIED SOLUTION
Avatar of Ajay-Singh
Ajay-Singh

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
definitely the first cat and second cat are different somehow, for example an space before or after the word "cat" => " cat"
Avatar of CEHJ
Try changing the split line to

wordList=reader.nextLine().split("\\s*,\\s*");
Actually forget that - Ajay's approach is better
Avatar of zizi21

ASKER

sorry..just finished two other exams..going back to java..forgive me for the late reply...