Simple analysis of Java Foundation---->HASHMAP (i)

Source: Internet
Author: User

HashMap is a very common data structure object that can hold key-value pairs. It's used more in the project, and today we're going to learn a little bit about it.

HashMap simple use of a, HashMap put and get method
New Hashmap<>(); Map.put ("username", "HUHX"), Map.put ("password", "1234"); Map.put ( NULL NULL ); System.out.println (Map.put (///  HUHX, this will return //  LinuxSystem.out.println ( Map.get (null//  null Size:3

The Put (key, value) method if there is a value in the map that calculates the key based on the hash. The result of the return is the OldValue value in map. But the value of the key in the map is updated to value.

Second, the Putall method of HashMap
 Public void extends extends V> m) {    ...      for extends extends V> E:m.entryset ())        put (E.getkey (), E.getvalue ());}

Third, the clear method in HashMap

The clear () method clears all the data in the map, and the map size is 0.

 Public void Clear () {    Modcount++    ; NULL );     = 0;}

Iv. method of Remove in HashMap

Note that the following two methods are followed by the above map.

// Linux, Size:2 // NULL, Size:2

The source method of the Remove method is as follows:

 Public V Remove (Object key) {    Entry<K,V> e = removeentryforkey (key);     return NULL NULL : E.value);}

The Containkey method in HashMap

Check if there is a corresponding key in the map.

 Public Boolean ContainsKey (Object key) {    returnnull;}

Several traversal modes of map

map<string, string> map = new hashmap<> (); Our map uses generics, here's a note.

First, EntrySet () traversal in HashMap
iterator<map.entry<string, string>> Iterator = map.entryset (). Iterator ();  while (Iterator.hasnext ()) {    map.entry<string, string> Entry = iterator.next ();     = Entry.getkey ();     = Entry.getvalue ();    System.out.println ("key=" + key + "value=" + value);}

Second, For-each circulation entryset
 for (map.entry<string, string> entry:map.entrySet ()) {    = entry.getkey ();     = Entry.getvalue ();    System.out.println ("key=" + key + "value=" + value);}

Third, For-each circulation keyset
 for (String key:map.keySet ()) {    System.out.println ("key=" + key + "value=" + Map.get (key));}

For each of the above, the map can store key null data. So when you traverse the map to take the key, if it is a string. It is best to cast a strong turn instead of calling the ToString () method.

A brief description of the HashMap principle

The HASHMAP data is stored in a entry array, new HashMap (), the initial capacity of the HASHMAP is set to 16, and the load factor is 0.75.

 PublicHashMap (intInitialcapacity,floatloadfactor) {    if(Initialcapacity < 0)        Throw NewIllegalArgumentException ("Illegal initial capacity:" +initialcapacity); if(Initialcapacity >maximum_capacity) initialcapacity=maximum_capacity; if(loadfactor <= 0 | |Float.isnan (loadfactor))Throw NewIllegalArgumentException ("Illegal load factor:" +loadfactor);  This. Loadfactor =Loadfactor; Threshold=initialcapacity; Init ();}

where the init () method can be overridden by a subclass that implements HashMap, adding its own processing logic when initializing the map. The data inside the HashMap is done by the following array, which is a high efficiency because it is an array.

transient entry<k,v>[] table = (entry<k,v>[]) empty_table;

Second, HashMap mainly involves the put and get of key-value pairs, here we discuss its put method

1  Publicv put (K key, V value) {2     if(Table = =empty_table) {3Inflatetable (threshold);//If the table array is empty, it is initialized to an array of size 16 with a load factor of 0.75. 4     }5     if(Key = =NULL)6         returnPutfornullkey (value);7     inthash = hash (key);//calculate its hash value according to key8     inti =indexfor (hash, table.length);9      for(entry<k,v> e = table[i]; E! =NULL; E =e.next) {Ten Object K; One         if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) { AV OldValue =E.value; -E.value =value; -E.recordaccess ( This); the             returnOldValue; -         } -     } -  +modcount++;//record the number of HashMap changes - addentry (hash, key, value, I); +     return NULL; A}

Line 9th to line 15 deals with the logic that the put key already exists when it is processed. is to return to OldValue, and the new value of the update key is values. Here we mainly look at the AddEntry method.

void addentry (intint  bucketindex) {    if (size >= threshold) & & (null ! = Table[bucketindex])) {        Resize (2 * table.length)        ; = (null ! = key)? Hash (key): 0;         = Indexfor (hash, table.length);    }    Createentry (hash, key, value, Bucketindex);}

Since the array maintained inside the HashMap is created, the size is 16. When key becomes more and more, the Bucketindex (Subscript of table array) is repeated. That is, the bucketindex is about to be inserted where the data is already available. When this happens, it increases the capacity by one hashmap, recalculates the hash and the position to insert the array. The last Createentry method is to store the value of the Key,value in the table array as follows.

void createentry (intint  bucketindex) {    Entry<K,V> e = table[ Bucketindex];     New Entry<>(hash, key, value, e);    Size+ +;}

The following is an enclosed HashMap get code:

 Public V get (Object key) {    ifnull)        return  getfornullkey ();    Entry<K,V> Entry = getentry (key);     return NULL NULL : Entry.getvalue ();}

The data type of the table array entry class is as follows:

Static classEntry<k,v>ImplementsMap.entry<k,v> {    FinalK Key;    V value; Entry<K,V>Next; intHash; /*** Creates new entry. */Entry (intH, K K, v V, entry<k,v>N) {value=v; Next=N; Key=K; Hash=h; }     Public FinalK GetKey () {returnkey; }     Public FinalV GetValue () {returnvalue; }     Public Finalv SetValue (v newvalue) {v OldValue=value; Value=NewValue; returnOldValue; }     Public Final Booleanequals (Object o) {if(! (Oinstanceofmap.entry))return false; Map.entry e=(map.entry) o; Object K1=GetKey (); Object K2=E.getkey (); if(K1 = = K2 | | (K1! =NULL&&k1.equals (K2))) {Object V1=GetValue (); Object v2=E.getvalue (); if(v1 = = V2 | | (V1! =NULL&&v1.equals (v2))) return true; }        return false; }     Public Final inthashcode () {returnObjects.hashcode (GetKey ()) ^Objects.hashcode (GetValue ()); }     Public FinalString toString () {returnGetKey () + "=" +GetValue (); }    /*** This method was invoked whenever the value in an entry was * overwritten by an invocation of put (k,v) for a K     EY K that's already * in the HASHMAP. */    voidRecordaccess (hashmap<k,v>m) {}/*** This method is invoked whenever the entry are * removed from the table. */    voidRecordremoval (hashmap<k,v>m) {}}
Entry

Friendship Link

Simple analysis of Java Foundation---->HASHMAP (i)

Related Article

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.