• Post Reply Bookmark Topic Watch Topic
  • New Topic

Hashcode of a string - reliable ?  RSS feed

 
Arjun Singh Rampal
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am making a simple java program. I want to take a string, get its hashcode and store it in a hash table along with that string. When i want to see if a given string exists in my hashtable, I will convert the given string to hashcode and then get the value which corresponds to that hashcode in my hashtable.
Are there any shortcomings in this method ? Can you suggest how to implement such code ?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would you not just use a Set?
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Specifically, a HashSet.

Or if you're implementing your own, perhaps for a class, then it sounds like you may need to consider what happens if two different strings have the same hashcode. Can you store more than one string with a given hashcode? And what happens if someone asks if your hashtable contains a given string X, and instead it has a different string Y which happens to have the same hashcode? Each of these problems is solvable, and in fact has been solved in any standard hashtable implementation. But if you're making your own, you need to be sure you're handling these possibilities.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Beware that it is perfectly ok for two different strings to have the same hashcode. So you cannot use the hashcode alone to check if a certain string is in your collection.

By the way, what you describe is partly what HashMap and HashSet already do for you. It's not necessary to implement this yourself, other than maybe for learning purposes.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arjun Singh Rampal wrote:I want to take a string, get its hashcode and store it in a hash table along with that string.

As others have said, a HashSet would be much better. And just for future reference: java.util.Hashtable is a legacy class; you should probably use a HashMap if you need such a structure.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!