我们有一个非关键标签,其值为字符串。我们想要检查标签值的变化。但我们不想进行字符串比较,因为这涉及客户端-服务器,而是我们想计算字符串的某种值并使用该值来帮助检测字符串更改。由于字符串不是关键的,我们想知道是否有一个非常简单且快速的解决方案来计算这样的值,以帮助检测字符串的更改。
最佳答案
使用.hashCode()
String.hashCode()
并不完美,因为它是有损的。因此字符串可能会发生变化并且具有相同的哈希码。 (但这不会经常发生)几乎每次字符串更改时,其哈希码也会更改。
所以你知道你要做什么,String.hashCode()
的代码是这样的:
public int hashCode() {
int h = hash; // the cached hash value
int len = count; // the number of characters in the string
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
关于java - 有没有一种方法可以快速计算字符串的签名以帮助检测字符串更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10519902/