Get to know java-15.7 Map from scratch (4)-Introduction to how HashMap works-hash collisions (often as interview questions)

Source: Internet
Author: User

In this chapter we will discuss the hash collision.

1. What is a hash collision?

Is the hashcode of the two object's key is the same, how to get his value at this time?

The answer is to traverse the entry linked list above the table at that position through equals.


2. Example

A normal example:

Package Com.ray.ch14;import Java.util.hashmap;public class Test {public static void main (string[] args) {hashmap< person, dog> map = new Hashmap<person, dog> (); Person person_1 = new person ();p erson_1.setheight (;p erson_1.setid (1);p erson_1.setname ("person_1"); Person person_2 = new person ();p erson_2.setheight;p Erson_2.setid (2);p erson_2.setname ("person_1");D og dog_1 = new Dog ();d Og_1.setid (1);d og_1.setname ("dog_1");D og dog_2 = new Dog ();d Og_2.setid (2);d og_2.setname ("dog_2"); Map.put ( Person_1, dog_1); Map.put (person_2, dog_2); System.out.println ("--" + Map.get (person_1). GetName ()); System.out.println ("--" + Map.get (person_2). GetName ());}} Class Dog {private int id = 0;private String name = "";p ublic int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic int hashcode () {System.out.println ("dog ' s Hashcode () invoked"); return ID;} @Overridepublic Boolean equals (objecT obj) {System.out.println ("dog ' s Equals invokes"); return super.equals (obj);}} class Person {private int id = 0;private String name = "";p rivate int height = 0; @Overridepublic int hashcode () {System.ou T.PRINTLN ("Person ID:" + ID + ", hashcode () invoked," + "Hashcode:" + this.name.hashCode () + this.height); return SUPER.HASHC Ode ();} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getheight () {return height;} public void setheight (int height) {this.height = height;} @Overridepublic String toString () {return ' ID: ' + ID + '; Name: "+ THIS.name +"; Height: "+ this.height;} @Overridepublic boolean equals (Object obj) {System.out.println ("ID:" + id + ", equals invokes"); return super.equals (obj); }}


Output:

Person Id:1,hashcode () invoked,hashcode:443164103180
Person Id:2,hashcode () invoked,hashcode:443164103180
Person Id:1,hashcode () invoked,hashcode:443164103180
--dog_1
Person Id:2,hashcode () invoked,hashcode:443164103180
--dog_2


Explain:

(1) Create two classes above, then add output statements to the hashcode and equal methods respectively

(2) through the output can be seen, in fact, we rewrite the Equals method is not called, we just need to hashcode to locate the corresponding object


Hash Collision Code:

Package Com.ray.ch14;import Java.util.hashmap;public class Test {public static void main (string[] args) {hashmap< person, dog> map = new Hashmap<person, dog> (); Person person_1 = new person ();p erson_1.setheight (;p erson_1.setid (1);p erson_1.setname ("person_1"); Person person_2 = new person ();p erson_2.setheight;p Erson_2.setid (2);p erson_2.setname ("person_1");D og dog_1 = new Dog ();d Og_1.setid (1);d og_1.setname ("dog_1");D og dog_2 = new Dog ();d Og_2.setid (2);d og_2.setname ("dog_2"); Map.put ( Person_1, dog_1); Map.put (person_2, dog_2); System.out.println ("--" + Map.get (person_1). GetName ()); System.out.println ("--" + Map.get (person_2). GetName ());}} Class Dog {private int id = 0;private String name = "";p ublic int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic int hashcode () {System.out.println ("dog ' s Hashcode () invoked"); return ID;} @Overridepublic Boolean equals (objecT obj) {System.out.println ("dog ' s Equals invokes"); return super.equals (obj);}} class Person {private int id = 0;private String name = "";p rivate int height = 0; @Overridepublic int hashcode () {System.ou T.PRINTLN ("Person ID:" + ID + ", hashcode () invoked," + "Hashcode:" + this.name.hashCode () + this.height); return this.name.h Ashcode () + this.height;//rewrite place}public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getheight () {return height;} public void setheight (int height) {this.height = height;} @Overridepublic String toString () {return ' ID: ' + ID + '; Name: "+ THIS.name +"; Height: "+ this.height;} @Overridepublic boolean equals (Object obj) {System.out.println ("ID:" + id + ", equals invokes"); return super.equals (obj); }}

Output:

Person Id:1,hashcode () Invoked,hashcode:443164103180person Id:2,hashcode () Invoked,hashcode:443164103180id:2, equals Invokesperson Id:1,hashcode () invoked,hashcode:443164103180id:1, equals Invokes--dog_1person id:2,hashCode () Invoked,hashcode:443164103180--dog_2

Explain:

(1) We rewrite the person, that is, the Hashcode method of key, artificially generated hash collision phenomenon

(2) from the output can be seen, the above code needs to use the Equals method


Return the put and get source code;

Here is the source of the put:

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))) {//Note place                V oldValue = e.value;                E.value = value;                E.recordaccess (this);                return oldValue;            }        }        modcount++;        AddEntry (hash, key, value, I);        return null;    }

Here is the source of get:


Public V get (Object key) {        if (key = = null)            return Getfornullkey ();        int hash = hash (Key.hashcode ());        for (entry<k,v> e = table[indexfor (hash, table.length)];             E! = null;             E = e.next) {            Object k;            if (E.hash = = Hash && (k = e.key) = = Key | | key.equals (k))//Note place                return e.value;        return null;    }

Please note that I noted above the note "Place of attention":

(1) If there is no hash collision, the previous two hash comparison plus the address of the key to the comparison can be, and then a "short-circuit" phenomenon, so that after the sentence is no longer executed.

(2) But in the case of a hash collision, the first two conditions are established, and then the last equals must be used to determine the equality of the objects.


A 3.hash collision scene?

(1) Generally appears in large data situations

(2) The generation method of Hashcode is weak (such as the artificial production hashcode above)


Summary: This chapter mainly through the introduction of hash collision once again in-depth understanding of hashmap work principle.


This chapter is here, thank you.

-----------------------------------

Directory




Get to know java-15.7 Map from scratch (4)-Introduction to how HashMap works-hash collisions (often as interview questions)

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.