• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problems making an unique ID for every word  RSS feed

 
Robert Pedersen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

I have problems with making an unique (int) ID for every word. I find it a little difficult to explain, but a simplified version of my program can clear up:



Here you can see that very short words like add goes fine, but when a command like "remove" gets typed, the number will be "114101109111118101", which is far bigger than an int, and my longest command gets the number 117110102114105101110100115. So my question is, is it any smart method to do this, to make a unique int for every word (if i makes it easier, the longest word I need is 9 characters long)?

Best regards,

Robert Pedersen
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use the hashcode of String.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Javaranch.
 
Robert Pedersen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wouter Oet wrote:You could use the hashcode of String.

That worked Thanks a lot for such a quick answer!

Wouter Oet wrote:And welcome to the Javaranch.

Thanks agian

Best regards,
Robert Pedersen
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Robert: note that those are not unique -- multiple Strings can share the same hashCode value. In fact, they must!

I hate to break it to you, but 32 bits isn't enough to create a unique code for every 9-character String. Even if we limit the Strings to lower-case ASCII, so there are nine characters with 26 choices for each, that's 26^9 different Strings, or 5429503678976. A 32-bit integer can hold only 4294967296 different values -- it's too small by a factor of 1000 to uniquely identify every nine character String.

If you use a Java long, though, that would be big enough!
 
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
For a more detailed explanation, see: hashCode : Java Glossary

Especially look at the heading HashCode Misconceptions, where it says:
Uniqueness: Some people try to use HashCodes as unique identifiers. You can’t count on hashCodes to be unique. They way they are properly used, this does not cause any serious problem.

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!