Java Basic Parsing series (11)---equals, = =, and Hashcode methods

Source: Internet
Author: User

Java Basic Parsing series (11)---equals, = =, and Hashcode methods directory
    • Java Basic Parsing series (i)---String, stringbuffer, StringBuilder
    • Java Basic Parsing series (ii)---integer cache and bin unpacking
    • Java Basic Parsing Series (iii)---hashmap principle
    • Java Basic Parsing Series (iv) The principle of---linkedhashmap and the implementation of LRU algorithm
    • Java Basic Parsing series (V)---hashmap problems and differences between Hashtable and Currenthashmap
    • Java Basic Parsing series (vi)---annotation principle and use
    • Java Basic Parsing Series (vii)---threadlocal principle analysis
    • Java Basic Parsing Series (eight)--fail-fast mechanism and principle of copyonwritearraylist
    • This is my blog directory, welcome to read
==
    • Basic data Type = = Compares a value
type Number of bytes
Float 4
Double 8
Byte 1
Short 2
Int 4
Long 8
Char 2
Boolean
    • Non-basic data types, which are reference variables, = = Compare the memory addresses pointed to
equals
    • The Equals method inside of the object class is compared with = =, which is the comparison address
public boolean equals(Object obj) {        return (this == obj);    }
    • And if not, the Equals method is overridden, such as if the contents of the string inside equals of string are the same
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 Effect
    • If there is no Hashcode method, the element that is added to a set (not allowed to repeat), then you have to check all the elements of the equals, if there is a Hashcode method, the hashcode of an object will be mapped to a position, in this position to check whether there is, So there is no need to check all. You can look at the put method of HashMap.
public V put(K key, V value) {        if (key == null)            return putForNullKey(value);        int hash = hash(key.hashCode());        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;    }
    • From the source can see, first through the hash value to find the position in the table, and then to find, thus reducing the number of times to execute equals
Equals Method and Hashcode method
    • The Equals method returns True,hashcode must be the same
    • The Equals method returns Flase,hahscoe not necessarily different
Modified the Equals method
    As the
    • has already known, the equals of object returns two objects with the same memory address, and subclasses of the object class often rewrite the Equals method, such as two people objects, compared to the memory addresses of two people objects. Instead, compare attributes such as name,age, as long as name and age are the same object
    • if you override only equals without overriding the Hashcode method, test
  public static void Main (string[] args) throws Exception {HashMap hashmap=new hashmap<person,integer&        gt; ();        Person P1=new person ("Jiajun", 18);        Person P2=new person ("Jiajun", 18);        System.out.println ("These two objects should be the same when set up");        Hashmap.put (p1,666);        System.out.println ("Then according to our design ideas, we through the P2 should be able to get 666");        System.out.println (Hashmap.get (p2)); System.out.println ("But this time the output is null");}    Class person{String name;    int age;        Public person (String Name,int age) {this.name=name;    This.age=age;        } @Override public boolean equals (Object obj) {if (this = = obj) {return true;        } if (obj = = null) {return false;        } if (This.getclass ()!=obj.getclass ()) {return false;        } people P = (people) obj;    Return This.name.equals (p.name) && this.age = = P.age; }}
    • As you can see from the experimental results, if you override the Equals method without overriding the Hashcode method, you are prone to problems.
Effective Java recommendations
    • As long as the information used in the comparison operation of the Equals method is not modified during program execution, the Hashcode method must consistently return the same integer if the same object is called multiple times.
    • If two objects are equal to the equals comparison, then the Hashcode method of the two objects must return the same integer result
    • If the equals comparison is different for two objects, then this two object Hahscode method does not necessarily return a different integer
I think sharing is a kind of spirit, sharing is my pleasure, not to say I think I said must be right, I said may be a lot of wrong, but I hope I said something is my life experience and thinking, is to give a lot of people to reflect on, maybe give you a second, half a second, even if a word a little bit of truth, triggered their This is my greatest value. (This is my favorite word, but also I write the original intention of the blog)

Jiajun Source: http://www.cnblogs.com/-new/
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility. If you feel that there is help, you can click on the lower right corner of the "recommendation", hoping to continue to bring good technical articles for everyone! Want to make progress with me? Then "pay attention" to me.

Java Basic Parsing series (11)---equals, = =, and Hashcode methods

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.