About hashcode

First, why the need hashcode

  The hashcode exists, in order to more efficiently query. In some hash container, if you want to determine whether or query some of the objects in the container, you need to use equals () constant comparison, but for a slightly larger amount of data when it is very slow,

   In this case, we can simplify the process, each object has a corresponding hashcode, hashcode first determines whether there is, with the premise of the presence equals () comparison. So, it can work more efficient. In fact use of the hash table, hashcode as a key, as a target value, given in a manner of storing key
thereof illustrated as follows
Here Insert Picture Description

  Hash provisions equal hashcode, a hash value that is equal to two key-value pairs. However hash values ​​are equal, not necessarily draw key-value pairs are equal. (Added: two different key-value pairs, equal hash value, which is the hash collision.)

  So it would attract states: two objects by equals () method when comparing equal, then their hashCode values must also ensure equal ( this is also rewrite the equals (), need to override hashCode () reasons ), but equal attention hashCode, equals may not be equal

Two, object of equals () and hashCode ()

1, equals () Source:

public boolean equals(Object obj) {
        return (this == obj);
    }

2, hashCode () source code
  for the object is a native hashCode method, see implemented, hashCode said annotation is a value returned by the object obtained storage address conversion, and object storage address correspondence hashcode.
Suppose we define a student from class

        student  s1= new student("李明");
        student  s2= new student("李明");

   Even if these two objects the same content, but different store addresses, hashcode should also be different, which meets the requirements

Three, equals () and hashCode () rewrite

In string class equals () and hashCode () Code Example

1, equals () Source:

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;
    }

    Seen, return address are not true simultaneously, while phase content returns true, then the corresponding hashCode () also rewritten

2, hashCode () Code

  public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;
        for (int i = 0; i < value.length; i++) {
             h = 31 * h + val[i];
           //注意:根据string串内容转化hash
        }
        hash = h;
        //目的为再次碰到可直接输出hashcode
    }
    return h;
}

  This rewriting, as long as both strings string content, the same as the corresponding the hashCode, satisfies a predetermined

Third, rewrite equals () without rewriting hasCode () consequences

  Suppose we have created a good student class, override equals () is equal to the content is the same, run the code below

public class HashMapTest {

    public static void main(String[] args) {
        HashMap<Student, String> map = new HashMap<Student, String>();
        // 这里key为new一个对象
        map.put(new student("李明"), "1");
        String s = map.get( new student("李明"));
        System.out.println(s);
    }

Operating results is null, and we think should be able to find a

  This is why, since we just rewrite the equals (), is not overridden hashCode (), so the student objects to generate hashcode method is a method in object, hashcode is transformed from the address, and new out of two two different objects, there is such a result, so we need to override hashCode () can solve this problem.

  In general, if you do not use the hash container, such as a map, etc., equals () and hashCode () it does not matter, but if you use a hash container, it is necessary to pay attention to the custom class equals () and hashCode ()

Released seven original articles · won praise 5 · Views 230

Guess you like

Origin blog.csdn.net/qq_43646059/article/details/104732275