How to convert a String into an id or numerical data?

Asked

Viewed 191 times

2

I have strings that are unique and would like to create an id from it.

Does anyone know how I can do?

Thank you in advance.

  • I think String’s hashcode method might help you. You loop your string collection and call this method for each string, saving the result as the id you want.

  • 1

    What is your goal? Hashes do not generate unique values and sooner or later there may be collision.

1 answer

4


The method hashcode() of the String class transforms the String representation into an integer number.

Example in Java:

public static void main (String[] args) throws java.lang.Exception
{
    String[] strings = {"abc","def","ggh","rrt"};

    for(int i = 0; i < strings.length;i++)
        System.out.println(strings[i].hashCode());
}

This code will print the following sequence:

96354 //abc
99333 //def
102280 //ggh
113204 //rrt

See working here.

Related question: Using hashcode as id is good practice?

  • exactly what I needed, thanks.

  • 1

    Only one warning: hashes do not generate unique values, that is, there can be collision with the same number being generated by two different strings. So it’s important for anyone who uses hashes to take this into account.

  • 1

    Yes @utluiz, this really needs to be taken into account. An example is the "[email protected]" and "[email protected]" strings. Both generate the same integer. Therefore, it depends on the context to which it is being applied. There are other hash functions, but as you said, there is no single value guarantee.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.