Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping of strings to integers

Tags:

java

What is the easiest way in Java to map strings (Java String) to (positive) integers (Java int), so that

  • equal strings map to equal integers, and
  • different strings map to different integers?

So, similar to hashCode() but different strings are required to produce different integers. So, in a sense, it would be a hasCode() without the collision possibility.

An obvious solution would maintain a mapping table from strings to integers, and a counter to guarantee that new strings are assigned a new integer. I'm just wondering how is this problem usually solved. Would also be interesting to extend it to other objects than strings.

like image 298
Kaarel Avatar asked Dec 20 '08 18:12

Kaarel


1 Answers

Have a look at perfect hashing.

like image 71
Dan Dyer Avatar answered Nov 08 '22 05:11

Dan Dyer