从字符串创建唯一的 id (int)

4fa*_*ace 3 java string android integer android-notifications

DocumentSnapshot from Firestore我有一个具有 id (字符串)的模型列表 ( )。我需要为每个通知创建一个通知,它们可能有很多(来自聊天的消息),并且我需要使用 int id 来分配给通知。我需要使用他们的字符串 ID,因为我可以收到该模型的更新版本,所以我想更新该精确模型的通知前端。有什么解决办法吗?

Gre*_*ggz 6

像这样做

int uniqueNumber = myString.hashCode()


rhk*_*coo 5

不可能从无限的字符串集中产生唯一的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());
    }
}
Run Code Online (Sandbox Code Playgroud)