从String创建唯一的id(int)

时间:2017-12-29 13:24:18

标签: java android string integer android-notifications

我有一个带有id(String)的模型列表(DocumentSnapshot from Firestore)。 我需要为每个人创建一个通知,它们可能很多(来自聊天的消息),我需要使用int id来分配通知。 我需要使用他们的String id,因为我可以收到该模型的更新版本,所以我想更新通知前面的精确模型。 什么可以解决方案?

4 个答案:

答案 0 :(得分:4)

从无限的字符串集中生成唯一 int id是不可能的。 但是你可以为你的目的使用一个好的哈希函数 - 在大多数情况下它会足够好。请考虑使用比普通#hashCode实现更好的东西。我建议你研究一下https://github.com/google/guava/wiki/HashingExplained

并至少使用murmur3算法。 代码段如下所示:

import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;

public class Main {

    public static void main(String[] args) {
        System.out.println(
                Hashing.murmur3_32()
                .newHasher()
                .putString("Some Sting", Charsets.UTF_8)
                        .hash().asInt());
    }
}

答案 1 :(得分:2)

感谢我找到了最佳解决方案:

public static int hashCode(String string) {
    return Hashing.murmur3_32()
            .newHasher()
            .putString(string, Charsets.UTF_8)
            .asInt());
} 

或者,String.hashCode()感谢Greggz& navy1978:

public static int hashCode(String string) {
    return string != null ? string.hashCode() * PRIME : 0;  // PRIME = 31 or another prime number.
}

或此@NonNull

public static int hashCode(@NonNull String string) {
    return string.hashCode() * PRIME;  // PRIME = 31 or another prime number.
}

答案 2 :(得分:1)

这样做

int uniqueNumber = myString.hashCode()

答案 3 :(得分:1)

你可以尝试,正如Greggz已经建议的那样,使用hashCode,例如,Eclipse建议这个实现(变量“b”是你的String):

public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((b == null) ? 0 : b.hashCode());
    return result;
}

当然,您可以根据自己的需要改变/调整它......