问题
From link :
http://www.tutorialspoint.com/java/java_string_hashcode.htm
Relationship between hashCode and equals method in Java
Good hashCode() Implementation
But i cant understand about the hashcode .
Here's an example:
public class StringDemo {
public static void main(String args[]){
String strob1="first string";
System.out.println(strob1.hashCode());
}
}
This simple program give me output:-5468287
Can anyone tell me :
How it give me output:-5468287
?
回答1:
String's hash code is computed as:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int
arithmetic, where s[i]
is the i
-th character of the string, n
is the length of the string, and ^
indicates exponentiation. (The hash value of the empty string is zero.)
Hence, the overflow of this integer computation can easily occur, resulting in negative according to Java Language specification-15.8.2:
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.
回答2:
In essence, you won't call it yourself unless you are coding a data structure (which you most probably don't have to).
However, you'll often implement one. Nowadays almost all IDE provide auto-generation of equals & hashCode. I'd advise to just use that for the moment; whenever you implement equals, also generate a hashCode implementation.
回答3:
Why? The method is defined in java.lang.Object. Any class you define inherits it.
Refer enter link description here.
What? I suggest you study more about what is hashing. Wiki hash functions.
回答4:
Hashcode is used to allow objects to be stored in a Map
object (or with other data structures that use hashes). The goal of a hashcode is to provide a unique value for objects with different values, but produce the same hashcode if the object is the same. This is essentially a unique index for an object to be looked up by.
A HashMap
, which implements the Map
interface, depends on a good implementation of hashcode()
to evenly distribute among differing objects for optimal performance. With this it can provide O(1) average case speed to operations such as get()
.
So if you ever intend on using a custom object that you make as a key
for a HashMap
you should provide an implementation of hashcode()
which most IDE's will assist you with.
edit: in your example output of -5468287
that is its hashcode value. If you look at the hashcode of "first strings"
which only differs by one character it should be a vastly different number, which is a good thing because it helps evenly distribute objects inside your Map.
来源:https://stackoverflow.com/questions/19985360/use-string-hashcode-method