Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

java - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, e.g.

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, e.g. sourceAddress instead of srcadd.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...