Programmer 400 Programmer 400 - 1 year ago 109
Java Question

Converting non-numeric String to Integer?

How can I convert a non-numeric String to an Integer?

I got for instance:

String unique = "FUBAR";

What's a good way to represent the String as an Integer with no collisions e.g. "FUBAR" should always be represented as the same number and shan't collide with any other String. For instance,
String a = "A";
should be represented as the Integer
and so on, but what is a method that does this (preferrably for all unicode strings, but in my case ASCII values could be sufficient).

Answer Source

This is impossible. Think about it, an Integer can only be 32 bits. So, by the pigeonhole principle, there must exist at least two strings that have the same Integer value no matter what technique you use for conversion. In reality, there are infinite with the same values...

If you're just looking for an efficient mapping, then I suggest that you just use the int returned by hashCode(), which for reference is actually 31 bits.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download