File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

weird problem with hash table

 
desmond60 wwkk
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Thanks
Desmond
 
John Dale
Ranch Hand
Posts: 399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 www.javaranch.com.
 
desmond60 wwkk
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi John
Our ClientKey had a equals method but no hashcode. ONce that was put in things seemed to work.
Thanks for the help
Desmond
 
Ron Newman
Ranch Hand
Posts: 1056
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You've learned an important lesson. NEVER override equals() without supplying a compatible hashCode() function.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic