aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Please go thru the code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Please go thru the code " Watch "Please go thru the code " New topic
Author

Please go thru the code

Venkat dasari
Ranch Hand

Joined: Nov 12, 2003
Posts: 67

The problem is the size of the hashmap is is 19998 but not 20000.
please someone explain why is it so?
[ Jess added UBB [code] tags to preserve whitespace, check 'em out! ]
[ February 13, 2004: Message edited by: Jessica Sant ]

Regards,<br />Venkat Dasari<br />SCJP 1.4, SCBCD.
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

When I ran your code the first time I got this (I made the println statements a bit more descriptive):

So as you can see, 4 of the objects you're trying to add into the HashMap have the same hashcode as 4 objects that are already in the HashMap. And as the name states, a HashMap stores keys according to their hashCode. So in the eyes of the HashMap -- those objects are identical -- so, when you call map.put() it simply replaces the 1st object with the same hashCode with this 2nd object.
So, how do you fix it? Every time you create a class that you want to add to a HashMap or HashTable, you need to override two very special methods: hashCode() and equals(). As we expained above, hashCode() is used to put keys into the HashMap, and equals() is used to pull things out (you test to see if two key objects are equal when you do a .containsKey() or .get())
Seeing as though the only attribute of your employee class is a String, I simply override the hashCode method to use the hashCode of the String itself, and the .equals() method simply checks to see if the hashCodes of the two objects are the same:

....check out the slides for the More Programming Puzzlers session at JavaOne 2003. The 2nd question they posed to the group had to deal with this kind of situation.
enjoy!
[ February 13, 2004: Message edited by: Jessica Sant ]

- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
Venkat dasari
Ranch Hand

Joined: Nov 12, 2003
Posts: 67
Many Many thanks Jessica.
thanks for helping me.
 
 
subject: Please go thru the code