简体   繁体   English

HashCode给出负值

[英]HashCode giving negative values

I am converting the incoming string into hash code by doing the following function but some of the values are negative. 我通过执行以下函数将传入的字符串转换为哈希码,但某些值为负值。 I don't think hash values should be negative. 我不认为哈希值应该是负数。 Please tell me what I am doing wrong. 请告诉我我做错了什么。

int combine = (srcadd + dstadd + sourceport + destinationport + protocol).hashCode();
System.out.println(combine);

I don't think hash values should be negative. 我不认为哈希值应该是负数。

Why not? 为什么不? It's entirely valid to have negative hash codes. 具有负哈希码是完全有效的。 Most ways of coming up with a hash code naturally end up with negative values, and anything dealing with them should take account of this. 提出哈希码的大多数方法自然会以负值结束,而处理它们的任何事情都应该考虑到这一点。 However, I'd consider a different approach to coming up with your hash codes, eg 但是,我会考虑一种不同的方法来提出你的哈希码,例如

int hash = 17;
hash = hash * 31 + srcadd.hashCode();
hash = hash * 31 + dstadd.hashCode();
hash = hash * 31 + sourceport; // I'm assuming this is an int...
hash = hash * 31 + destinationport; // ditto
hash = hash * 31 + protocol.hashCode();
return hash;

It's not clear what the types of these expressions are, but I'm guessing you're ending up taking the hash code of a string... a string that you don't really need to create in the first place. 目前尚不清楚这些表达式的类型是什么,但我猜你最终会得到一个字符串的哈希码...一个你不需要首先创建的字符串。 While there are better approaches for getting hash codes for known domains, the above approach works well as a general-purpose hash generation technique. 虽然有更好的方法来获取已知域的哈希码,但上述方法很适合作为通用哈希生成技术。

Note that it would also help the readability of your code if you avoided abbreviations, and used camel casing, eg sourceAddress instead of srcadd . 请注意,如果您避免使用缩写,并使用驼峰套管,例如sourceAddress而不是srcadd ,它也有助于您的代码的可读性。

sometimes the hashcode calculation itself goes beyond the Integer.MAX_VALUE , ie 2147483647 . 有时hashcode计算本身超出了Integer.MAX_VALUE ,即2147483647 what happens then is that we get a negative integer after the overflow . 然后发生的是我们在overflow后得到一个负整数。 Negative hashcode is perfectly valid! 负哈希码完全有效!

It is perfectly legal to have negative hash codes , and if you are looking for hash values as used in hash-based collections you can use Math.abs(hash) . 具有负哈希码是完全合法的,如果您正在查找基于哈希的集合中使用的哈希值 ,则可以使用Math.abs(hash) This can also give you negative numbers when hash is bigger than 2^31, and the best way would be to use a shift mask (key.hashCode() & 0x7fffffff) % M , where M is the table size. 当散列大于2 ^ 31时,这也可以给你负数,最好的方法是使用移位掩码(key.hashCode() & 0x7fffffff) % M ,其中M是表大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM