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("Incorr ect 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);
}
}
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("Incorr
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()
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);
}
}
also, note that
"cat" and "cat " are not equal
"cat" and "cat " are not equal
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
definitely the first cat and second cat are different somehow, for example an space before or after the word "cat" => " cat"
Try changing the split line to
wordList=reader.nextLine() .split("\\ s*,\\s*");
wordList=reader.nextLine()
Actually forget that - Ajay's approach is better
ASKER
sorry..just finished two other exams..going back to java..forgive me for the late reply...
please post the result of
System.out.println(hm);
after your for loop.