Must master the hashcode() method

What is hashcode?

If you want to know this hashcode, you must first know the hash. Look through Baidu Encyclopedia:

Insert picture description here

Hash is a function, and the implementation in this function is an algorithm, which is to get a hash value through a series of algorithms. At this time, we need to know another thing, the hash table. The hash value obtained through the hash algorithm is in this hash table. In other words, the hash table is composed of all the hash values. There are many kinds of hash functions, and It means that there are many algorithms to get the hash value, such as the three in the screenshot above, we will take the first one later.

hashcode

With the previous foundation, the explanation here is simple. The hashcode is obtained through the hash function. In layman's terms, it is obtained through a certain algorithm. The hashcode has a corresponding position in the hash table.

Every object has a hashcode, how is the hashcode of the object obtained?

First of all, an object must have a physical address. In other blog posts, the hashcode will be said to represent the address of the object. This will definitely cause readers to misunderstand that the physical address of the object is different from this hashcode address.Hashcode represents the address of the object and it refers to the position of the object in the hash table, and the physical address refers to the address where the object is stored in memory., Then how does the object get the hashcode?

The internal address of the object (that is, the physical address) is converted into an integer, and then the integer is obtained by the algorithm of the hash function to obtain the hashcode.So, what is hashcode? It is the corresponding position in the hash table.

If it is not very clear here, for example, there are eight positions in the hash table with hashcode of 1, hashcode of 2, (...) 3, 4, 5, 6, 7, and 8, and there is an object A, A The physical address is converted to an integer of 17 (this is what if), and by the direct remainder algorithm, 17%8=1, then the hashcode of A is 1, and A is in the position of 1 in the hash table.

There will definitely be other questions, then look at the following, here is just an example to let you know what is the meaning of hashcode.

What does hashcode do?

I have said so much about the hash function, how the hashcode is derived, and the hashcode corresponds to the location in the hash table. You may have questions about why the hashcode does not write the physical address directly, and you need to use another one. hash table to represent the address of the object? Next, I will tell you the role of hashcode,

::: info
HashCode exists mainly for the convenience of search. HashCode is used to determine the storage address of the object in the hash storage structure (the latter part of the sentence uses hashcode to represent the object in the hash table)
:::

Why does hashcode look up faster? For example, if we have a memory that can store 1000 numbers, we need to store 1000 different numbers in it. The most stupid way is to store a number and traverse it again. See if there are the same numbers. When you store 900 numbers and start to store 901 numbers, you need to compare with 900 numbers. This is very troublesome and time-consuming. Use hashcode to record the location of the object. take a look.

There are 1, 2, 3, 4, 5, 6, 7, and 8 positions in the hash table. The first number is stored, and the hashcode is 1, the number is placed in position 1 in the hash table, and 100 numbers are stored. There are many numbers in 8 positions in the hash table. There may be 20 numbers in 1. When storing 101 numbers, he first checks the position corresponding to the hashcode value. If it is 1, then there are 20 numbers that are the same as his hashcode. , He only needs to compare (equals) with these 20 numbers. If each is the same, put it in the position 1, so that the number of comparisons is much less. In fact, there are many positions in the hash table. Here is just an example. 8, so the number of comparisons will make you think a lot. In fact, if the hash table is large, the number of comparisons is very small.

By comparing the original method and the hashcode method, we know the role of hashcode and why hashcode is used

The relationship between equals method and hashcode?

Through the previous example, you can probably know that the hashcode is first compared. If the hashcode is equal, then the equals method is used to compare whether the two objects are equal.

Take an example to illustrate: the 8 positions in the hash table mentioned above are like 8 buckets. Each bucket can hold a lot of objects. Object A gets it through the hash function algorithm and puts it in bucket 1, of course. Other objects will also be placed in bucket 1. If object B is also assigned to bucket 1 through the algorithm, how does it recognize whether other objects in the bucket are the same as it? At this time, the equals method is needed to filter.

1. If the two objects are equals, then the HashCode of the two objects must be the same.
2. If the HashCode of the two objects is the same, it does not mean that the two objects are the same, which only means that the two objects are in the hash storage structure. , Stored in the same location

Why is it recommended to rewrite the hashcode method together if the equals method is rewritten?

If the equals method of the object is rewritten, then the HashCode method of the object is also rewritten as much as possible

For example, I actually understand this truth,

For example: A class A overrides the equals method, but does not override the hashCode method. Look at the output result, the object a1 and the object a2 use the equals method to be equal. According to the usage of the above hashcode, then the hashcodes of the two of them must be equal, but Since the hashcode method is not rewritten here, their two hashcodes are not the same, so,After rewriting the equals method, we try to rewrite the hashcode method as well, Through a certain algorithm, when equals equals, they will have the same hashcode value.

class A {
    
    
    private int age;

    public A(int age) {
    
    
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
    
    
        // 判断传入的类是否是A的实例
        if (obj instanceof A) {
    
    
            A a = (A) obj;
            if (a.age == this.age) {
    
    
                return true;
            }
        }
        return false;
    }
}
/**
 * Created by gysui on 2020/11/21
 */
public class TestEquals {
    
    



    public static void main(String[] args) {
    
    
        A a = new A(12);
        A a1 = new A(12);
        System.out.println(a.hashCode()); // 460141958
        System.out.println(a1.hashCode()); // 1163157884
        System.out.println(a.equals(a1)); // true
    }
}

Example: Now let’s look at the equals method and hashcode method in the String source code. This class rewrites these two methods. Why do you need to rewrite these two methods now?

Equals method : In fact, the principle is the same as the example I wrote above, so I know through the source code that the equals method of String verifies whether the values ​​of the two strings are the same. The Double class also rewrites these methods. Many classes have more of these two methods, because they are in the parent class Object of all classes. The function of equals is """ number. You can also compare equals andThe difference. No more explanation here.

public boolean equals(Object anObject) {
    
    
	if (this == anObject) {
    
    
		return true;
	}
	if (anObject instanceof String) {
    
    
		String anotherString = (String)anObject;
		int n = value.length;
		if (n == anotherString.value.length) {
    
    
			char v1[] = value;
			char v2[] = anotherString.value;
			int i = 0;
			while (n-- != 0) {
    
    
				if (v1[i] != v2[i])
					return false;
				i++;
			}
			return true;
		}
	}
	return false;
}

hashcode method

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43088443/article/details/112792133