问题描述:



I need to generate a unique integer id for a string.

Reason:

I have a database application that can run on different databases. This databases contains parameters with parameter types that are generated from external xml data.

the current situation is that i use the ordinal number of the Enum. But when a parameter is inserted or removed, the ordinals get mixed up:

(FOOD = 0 , TOYS = 1) <--> (FOOD = 0, NONFOOD = 1, TOYS = 2)



The ammount of Parameter types is between 200 and 2000, so i am scared a bit using hashCode() for a string.



P.S.: I am using Java.



Thanks a lot

网友答案:

I would use a mapping table in the database to map these Strings to an auto increment value. These mapping should then be cached in the application.

网友答案:

Use a cryptographic hash. MD5 would probably be sufficient and relatively fast. It will be unique enough for your set of input.

Generate MD5 hash in Java

The only problem is that the hash is 128 bits, so a standard 64-bit integer won't hold it.

网友答案:

If you know the type of string values (length, letter patterns), you can count the total number of strings in this set and if it fits within 32 bits, the count function is your integer value.

Otherwise, the string itself is your integer value (integer in math terms, not Java).

网友答案:

If you need to be absolute certain that the id are unique (no collissions) and your strings are up to 32 chars, and your number must be of no more than 10 digits (approx 32 bits), you obviously cannot do it by a one way function id=F(string).

The natural way is to keep some mapping of the string to unique numbers (typically a sequence), either in the DB or in the application.

网友答案:

By Enum you mean a Java Enum? Then you could give each enum value a unique int by your self instead of using its ordinal number:

public enum MyEnum {

    FOOD(0),
    TOYS(1),

    private final int id;

    private MyEnum(int id)
    {
        this.id = id;
    }
}
相关阅读:
Top