HashCode and javahashcode for JAVA Learning

Source: Internet
Author: User

HashCode and javahashcode for JAVA Learning

public native int hashCode();

Returns the hash value of the object. This method is supported to improve the hash table (for examplejava.util.HashtableHash table.

I. Role of HashCode

We usually use equals to determine whether the set contains an object. In this way, we need to traverse each element in the set and then compare them with the equals method one by one. This method is natural for a collection of a small amount of data, but when we have a lot of data, such as 10 thousand, it is obviously not appropriate to use this one-by-one Traversal method. So someone invented a hash algorithm to improve the efficiency of searching elements from the collection. The core of this method is to divide the set into several regions. Each object can calculate a hash code and group the hash code. Each group corresponds to a storage region, when searching for an object, we first determine that the object is stored in a region based on the object's hash code. Then, search for the elements in this area.

 

HashSet, HashMap, and HashTable in java are used together with the hashCode method.

The following code is the specific implementation of the put Method in java. util. HashMap:

 public V put(K key, V value) {        if (table == EMPTY_TABLE) {            inflateTable(threshold);        }        if (key == null)            return putForNullKey(value);        int hash = hash(key);        int i = indexFor(hash, table.length);        for (Entry<K,V> e = table[i]; e != null; e = e.next) {            Object k;            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {                V oldValue = e.value;                e.value = value;                e.recordAccess(this);                return oldValue;            }        }        modCount++;        addEntry(hash, key, value, i);        return null;    }

The put method is used to add new elements to the HashMap. According to the specific implementation of the put method, the hashCode method is called to obtain the hashCode value of the element, check whether the hashCode value exists in the table. If yes, call the equals method to re-determine whether the element exists. If yes, update the value, otherwise, add the new element to the HashMap. It can be seen from this that the hashCode method exists to reduce the number of calls to the equals method and thus improve program efficiency.

Ii. equals and HashCode

1. equals and HashCode must appear together.

In the put () method, why do I need to judge equals after judging HashCode?

Because different objects may generate the same hashcode value, we cannot determine whether the two objects are equal based on the hashcode value. However, you can directly judge two objects according to the hashcode value. If the hashcode values of two objects are not the same, they must be two different objects. To determine whether two objects are truly equal, you must use the equals method.

Therefore, we must rewrite the hashcode method when rewriting the equals method. The hash set first judges the hashCode value of the object when adding data. If the hashcode value is different, it is hashed to different storage regions, therefore, it makes no sense to compare equals. In this case, it violates the meaning of the Set (the set of repeated elements is not allowed ).

2. Ensure that the hashcode value of the object in the set cannot be changed.

When an object is stored in a hash set, you cannot modify the fields involved in calculating the hash value. Otherwise, the modified hash value of the object is not the same as the hash value when it was originally stored in the set. In this case, in the contains method, the current application of the object is used as the parameter to retrieve the object in the hash set. The object cannot be found, this will lead to the failure to delete the current object from the hash set separately, thus resulting in memory overflow.

Use HashSet to demonstrate:

Package com.jalja.org. base. test; import java. util. hashSet; import java. util. set; public class Point {private int x; private int y; public Point (int x, int y) {super (); this. x = x; this. y = y;} public int getX () {return x;} public void setX (int x) {this. x = x;} public int getY () {return y;} public void setY (int y) {this. y = y ;}@ Override public int hashCode () {final int prime = 31; int resu Lt = 1; result = prime * result + x; result = prime * result + y; return result ;}@ Override public boolean equals (Object obj) {if (this = obj) return true; if (obj = null) return false; if (getClass ()! = Obj. getClass () return false; Point other = (Point) obj; if (x! = Other. x) return false; if (y! = Other. y) return false; return true;} public static void main (String [] args) {Point point1 = new Point (1, 2); Point point2 = new Point (2, 3 ); point point3 = new Point (3, 4); Set <Point> set = new HashSet <Point> (); set. add (point1); set. add (point2); set. add (point3); System. out. println (set. size (); // 3 point1.setX (5); // change the x value of point1 to set. remove (point1); // remove point1 System. out. println (set. size (); // 3 }}

The result shows that point1 cannot be deleted.

 

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.