Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 616
Xara Avatar asked Feb 12 '12 15:02

Xara


People also ask

Does hashCode only return positive?

during the execution of the java application if the hashCode() method is called on the same object multiple times then the method must return the same integer value. 4. the object class has a hashCode() method that returns only positive integers.

Can HashMap have negative values?

Hashcode has type of int , so it can be negative and positive. But HashMap uses hashcode to determinate in which index of the table put key+value, like, hashcode / size_of_table = table_index .

What will happen if hashCode returns same value?

If multiple objects return the same value from hashCode(), it means that they would be stored in the same bucket. If many objects are stored in the same bucket it means that on average it requires more comparison operations to look up a given object.

What does the hashCode () method?

The Java hashCode() Method hashCode in Java is a function that returns the hashcode value of an object on calling. It returns an integer or a 4 bytes value which is generated by the hashing algorithm.


1 Answers

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.

like image 109
Jon Skeet Avatar answered Sep 28 '22 01:09

Jon Skeet