How to correctly implement Hashcode in Java

Source: Internet
Author: User

Origin: Open Source China

Equal and Hash Code

From a general point of view, equality is good, but hash code is more skillful. If we do a bit more on hash code, we can see that hash code is used to improve performance in subtle places.

Most of the data structures use equals to check if they contain an element. For example:

list<string> list = Arrays.aslist ("A", "B", "C"); Boolean contains = List.contains ("B");

This variable contains is true. Because they are equal, although the instantiation of B (instance) is not exactly the same (again, ignore string interning).

It is a waste of time to compare the instances passed to contains with each element. Fortunately, the whole type of data structure uses a more efficient approach. Instead of comparing the requested instance to each element, it uses a shortcut, finds an instance that might be equal to it, and then compares only those items.

This shortcut is a hash code-an integer value that can be computed from an object that represents the object. Instances with the same hash code do not have to be equal, but equal instances must have the same hash code. (or there should be, we'll have a brief discussion on this later on). This kind of data structure often uses this technique to name, adds the Hash in the name to identify, the most representative is HASHMAP.

In general, they do this:

    • When an element is added, its hash code is used to calculate the position (ordinal number) stored in the internal array (called the bucket).
    • Another non-identical element, if it has the same hash code, is placed in the same bucket, with the original one, such as placing them in a list.
    • If an instance is passed to the contains method, its hash code is evaluated first to find the bucket, and only the elements in the same bucket need to be compared with the instance.

It is very rare to use this method to achieve contains, and in an ideal state there is no need to compare equals.

Defines equals, hashcode in an Object.

Some thoughts on hashing

If Hashcode is used as a shortcut depending on whether it is equal, then there is only one thing we need to be concerned about: equal objects should have a consistent hash code.

This is also why, if we overwrite the Equals method, we must create a matching hashcode implementation! In addition, implementation of equal should be implemented according to our implementation, which may result in the absence of the same hash code, because they are using an Object implementation.

Hashcode conventions

References from the original document:

General conventions for Hashcode:

    • In a Java application, calling the Hashcode method multiple times on the same object at any time must always return the same integer, and the information it provides is also used for equality comparisons of objects and is not modified. This integer does not need to be consistent in the execution of the same application two times.
    • If two objects compare equal results by using the Equals (object) method, then the Hashcode method of the two objects must produce the same integer result.
    • If two objects use the Equals (object) method to compare the results, the hashcode of the two objects do not have to produce different integer results. However, developers should understand that producing different integer results for unequal objects can help improve the performance of the hash table.

The first article reflects the consistency of equals. The second is the request we mentioned above. The third article states an important detail that we will discuss below.

Implement Hashcode

The Person.hashcode has a very simple implementation:

@Override  Public int hashcode () {return  objects.hash (FirstName, lastName);}

By calculating the hash code of the related fields, the hash codes are combined to get the person's hash code. They use the tool function hash of Object to participate in the calculation.

Select field

But what is the relevant field? These requirements help answer the question: If equal objects must have the same hash code, then the fields that are not used for equality checking should not be used when calculating the hash code. (otherwise, if only those fields are different for two objects, they will be equal but hash codes are different.) )

So those fields that are used to calculate the hash code should be subsets of those fields used for equality comparisons. By default, they will use the same fields, but there are a few details to consider.

Consistency

The first is conformance requirements. It should undergo very rigorous calculations. If there is a change in the field, the hash code should also allow the change (which is often unavoidable for mutable classes), and the data structure that relies on hashing is not prepared to handle this situation.

As we saw above, the hash code is used to determine the bucket of an element, but if the hash-related field changes, the hash code is not recalculated immediately, and the inner array is not updated.

This means that a query against an equal object or even the same object will fail! This data structure calculates the current hash code, which is not the same as the hash code when the instance was deposited, which leads directly to the wrong bucket.

Summary: It is best not to use variable fields to calculate the hash code!

Performance

The hash code may end up being evaluated every time the equals is called, which can happen precisely in the code where performance is extremely critical, so it makes sense to consider performance. By contrast, the optimization space for equals is very small.

Unless a complex algorithm is used, or the fields used are very many, the computational cost of combining their hashes is negligible, as this is unavoidable. However, you should consider whether all fields need to be included in the calculation! In particular, the collection should be viewed with a view, such as calculating hash codes for all elements in lists and collections. It is necessary to consider whether or not they need to participate in the calculation depending on the situation.

If performance is critical, using object.hash may not be the best choice because it creates arrays for mutable parameters.

The general principle of optimization is: Handle it with care! With a common hashing algorithm, you may want to discard the collection and optimize it after you analyze the possible improvements.

Collision

If you only focus on performance, what about the following example?

@Override  Public int hashcode () {return 0;}

No doubt it was soon. And the equivalent of the object will have the same hash code, which makes us feel good. There's also a bright spot, it doesn't involve mutable fields!

But, think about what the bucket we mentioned is? In this case, all instances are loaded into the same bucket! Often this leads to the use of a linked list to accommodate all the elements, which is too bad-for example, a linear scan of the contains is performed every time the execution occurs.

So we have to keep the contents of each bucket as small as possible! A very different algorithm, even if the hash code is computed for very similar objects, would be a good start.

How to get to a certain extent depends on the selected field. The details we use for calculations are more often used to generate different hash codes. Note that this is the exact opposite of what we think about performance. The results are interesting, and using too many or too few fields can cause poor performance.

The collision avoidance algorithm is another part of the hashing algorithm.

COMPUTE Hash

The simplest way to calculate the hash code of a field is to call the ' hashcode ' of the field directly. You can merge by hand. A common algorithm is to start with any number, multiply it with another number (usually a small prime), add a hash code for a field, and then repeat:

int prime = +; int result = 1null)? 0null)? 0 : Lastname.hashcode ()); return result;

This can cause overflow, but this is not a big problem, because exceptions are not thrown in Java.

Note that if the input data has a specific pattern, the best hashing algorithms can have unusually frequent collisions. As a simple example, suppose we use the x-coordinate and the y-coordinate of a point to calculate the hash. It was not so bad at first, until we found a point on this line: f (x) =-X, these points x + y = 0. There will be a lot of collisions!

How to correctly implement Hashcode in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.