1. What is a HashCode method?

The hashcode method returns the hashcode value of an objectCopy the code
  • The HashCode method must return the same integer for multiple calls to the same object during the execution of the application, as long as the information used by the equals method to compare the object has not changed.
  • The existence of Hashcode is mainly used for quick lookup, such as Hashtable,HashMap, etc. Hashcode is used to determine the storage address of the object in the hash storage structure.

2. Relation between hashcode equality and object equality :(on the premise that design is normative)

  • If two objects are the same, the hashcodes of the two objects must also be the same.

  • If two objects have the same Hashcode, it does not necessarily mean that they are the same, that is, it does not necessarily apply to equals, but that they are stored “in the same basket” in the hash table storage structure.

3. Why overwrite HashCode

Every class that overrides equals must also override the hashCode method. Failing to do so violates the general convention of Object.hashCode, which reads as follows: from the Object specification [JavaSE6] :

  • The hashCode method must consistently return the same integer multiple times called on the same object during the execution of the application, as long as the information used by the equals method to compare the object has not been modified. During multiple executions of the same application, the integers returned by each execution can be inconsistent.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method of either Object must produce the same integer result.
  • If two objects are not equal according to the equals(Object) method, then calling the hashCode method of either Object does not necessarily produce different integer results. But programmers know that it is possible to improve the overall performance of a hash table by producing radically different integer results for objects that are not equal.

If we don’t override the hashCode method, we might not be able to use hashCode where we want to use it. Here’s an example of a class that only overwrites equals, but not hashCode:

package com.atguigu.nio; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class Tesz { private final String field01; public Tesz(String field01) { this.field01 = field01; @override public Boolean equals(Object o){if (this == o){return true; } if (o == null || getClass() ! = o.getClass()) { return false; } Tesz myObject = (Tesz) o; return (Objects.equals(field01, myObject.field01)); } public static void main(String[] args) { Map<Object, Object> map = new HashMap<>(); map.put(new Tesz("123"), "123"); System.out.println(map.get(new Tesz("123"))); }}Copy the code

If the value is null and the key is new MyObject(“123”), then the equals method is not guaranteed to be equal. This class violates hashCode’s convention. Since MyObject does not override the hashCode method, two equal instances have unequal hash codes. The PUT method puts the object in one hash bucket, and the GET method looks for the object in another hash bucket, which is obviously not found.

When we add the hashCode method, the results are displayed correctly.

// For how to write the hashCode method and what hash reference is returned, please refer to: http://blog.csdn.net/zuiwuyuan/article/details/40340355 @Override public int hashCode() { int result = field01.hashCode() * 17; return result; }Copy the code

Source code analysis why this situation, let’s take a look at Map source code is clear:

final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; /** * check if table is null */ if ((TAB = table)! = null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) ! = null) {/* * Efficiency considerations * always compare the first object, If meet the requirements directly return series of code * * avoid the loop preparation/if (first) hash = = hash && / / always check first node ((k = first. Key) = = key | | (key! = null && key.equals(k)))) return first; If ((e = first.next)! = null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); Do {/ / cycle internal use && operator of inertia, if the hash code is not the same, it just skip = = if (e.h ash = = hash && ((k = e.k ey) = = key | | (key! = null && key.equals(k)))) return e; } while ((e = e.next) ! = null); } } return null; }Copy the code

The PUT method stores the phone number object in one hash bucket, while the GET method looks in another. Even if the two instances happen to be in the same hash bucket, the get method will always return NULL, because HashMap is optimized to store the hash code associated with each item. If the hash code does not match, the object is not checked for equality, taking full advantage of logic and computational inertia (&&).

4. How do I override hashCode while overriding equals?

In fact, the problem is as simple as overriding the hashCode method and returning an appropriate Hash code.

@Override
public int hashCode() {
return 42;
}
Copy the code

This does solve the above problem, but in practice, it leads to poor performance because it always ensures that every object has the same hash code. Therefore, each object is mapped to the same hash bucket, reducing the hash to a linked list.

A good hash function tends to “produce different hash codes for unequal objects”. Ideally, a hash function should distribute unequal instances of a set evenly over all possible hash values. But in practice, achieving this ideal situation is very difficult.

How to set up a good hash function?

A. Compute a hash code of type int for an object:

  • – For Boolean types, calculate (f? 1-0)
  • – For byte,char,short,int, calculate (int)f
  • – For long, evaluate (int)(f^(f>>>32))
  • – For float type, calculate float.floattointbits (f)
  • – For Double, Double. DoubleToLongBits (f) is evaluated, and then treated as long
  • – For object references, and the class’s equals method compares the field by recursively calling equals, it also recursively calls HashCode for that field
  • – For arrays, each element is treated as a separate field.

B. Result = 31 * reuslt + c;

C. returns the result

For example, we could optimize the hashCode method above:

 @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + areaCode;
        result = 31 * result + prefix;
        result = 31 * result + lineNumber;
        return result;
    }
Copy the code

If a class is immutable and it is expensive to compute the hash code, you should consider caching the hash code inside the object rather than recalculating the hash code on every request.

private volatile static int hashcode;

    @Override
    public int hashCode() {
        int result = hashcode;
        if (result == 0){
            result = 31 * result + areaCode;
            result = 31 * result + prefix;
            result = 31 * result + lineNumber;
            hashcode = result;
        }
        return result;
    }
Copy the code

Why 31?

Because it is an odd prime, it also has a nice property that it can get better performance by shifting and subtracting instead of multiplication:

31*i == (i<<5)-i
Copy the code

4. References

www.cnblogs.com/Tony-Anne/p… www.jianshu.com/p/40ee40f15…

Pay attention to the public account “Programmer interview”

Reply to “interview” to get interview package!!

This public account to share their own from programmer xiao Bai to experience spring recruitment autumn recruitment cut more than 10 offer interview written test experience, including [Java], [operating system], [computer network], [design mode], [data structure and algorithm], [Dacheng face by], [database] look forward to you join!!

1. Computer network —- Three times shake hands four times wave hands

2. Dream come true —– Project self-introduction

Here are the design patterns you asked for

4. Shocked! Check out this programmer interview manual!!

5. Teach you the interview “Profile” word for word

6. Nearly 30 interviews shared

7. Here are the free books you asked for