File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes weird problem with hash table Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "weird problem with hash table" Watch "weird problem with hash table" New topic

weird problem with hash table

desmond60 wwkk

Joined: Oct 13, 2002
Posts: 2
Hi there
I'm having a problem with a hashtable. I use an object called ClientKey as my key value, and this object called Message as my value.
So, i create an object called clientkey and put that in the hashtable with a Message object for it's value. Now, if i check to see that the key i just added is still in there i use hashTable's "containsKey()" function and it tells me that the key and it's value are in there.
So, here's my problem. I put in a key and a value, but then later on, i create a new key and then try to look it up to see if it's in the hashtable. This should return me true when i call "containsKey()" but it doesn't. If i get an enumeration of all the keys from the hashtable and then compare each to the key that i've created i will get a match, but for some reason "containsKey" returns false.
Can anyone give some advice?
John Dale
Ranch Hand

Joined: Feb 22, 2001
Posts: 399
Perhaps you didn't write an equals(Object) and hashCode() method for your ClientKey class. That would give the behavior I think you described.
You are in luck. There is a article on this in this month's JavaRanch newsletter, accessible via
desmond60 wwkk

Joined: Oct 13, 2002
Posts: 2
Hi John
Our ClientKey had a equals method but no hashcode. ONce that was put in things seemed to work.
Thanks for the help
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
You've learned an important lesson. NEVER override equals() without supplying a compatible hashCode() function.

Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
It's important to realize that HashMap and HashSet use the hash method to determine position within the hash object. Failure to override them may mean that your object can't be found in the hash object.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
I agree. Here's the link:
subject: weird problem with hash table
It's not a secret anymore!