Java – a good hash function for accessing integers and strings?

I encountered some situations in the interview. I need to use integer or string hash function In this case, what should we choose? I made a mistake in these cases, because I finally chose those things that produce a lot of collisions, and then the hash function is often mathematical. You can't recall it in the interview Is there any general suggestion that at least the interviewer is satisfied with your integer or string input method? In the "interview situation", which functions are sufficient for both inputs

Solution

This is a simple recipe for effective Java page 33:

>Store non-zero values of some constants in an int variable called result, such as 17. > For each important field F in your object (each field is considered by the equals method, i.e., by...), do the following:

>Calculate the int hash code c of the field:

>If the field is a Boolean value, (f? 1:0) is calculated. > If the field is a byte, char, short or int, then compute (int) F. > if the field is long, compute (int) (f ^ (F > > > 32)). > If the field is a floating point number, float. Is calculated floatToIntBits(f). > If the field is double, double Doubletolongbits (f) and then as in step 2.1 The hash result in III is long. > If the field is an object reference and the equals method of the class, compare the field by calling equals recursively, and call hashcode on the field If it is complicated, you need to calculate the "specification representation" of this field and call hashcode on the specification representation If the value is null, the field returns 0 (or some other constant, but 0 is traditional) Method common to all objects > if the field is an array, treat it as if each element is a separate field That is, the hash code of each valid element is calculated by application. These rules are recursive, and each step is 2 B combine these values If the array field in each element is important, you can use one of the arrays. Fields added in version 1.5 Hashcode method

>Combine the hash code c calculated in step 2.1 with the following results: result = 31 * result c;

>Return result. > After writing the hashcode method, ask yourself that equal instances have equal hash codes Write unit tests to verify your intuition! If equal instances have unequal hash codes, you can figure out why and solve the problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>