从String创建唯一的id(int)[关闭]

问题描述 投票:1回答:4

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

java android string integer android-notifications
4个回答
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());
    }
}

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.
}

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;
}

当然,你可以改变/适应你的需求......


1
投票

像这样做

int uniqueNumber = myString.hashCode()

© www.soinside.com 2019 - 2024. All rights reserved.