We talk about the common face test HASHMAP_ advanced

Source: Internet
Author: User
Tags prev
The main difference between HashMap and Hashtable.

1. Parent Source: Inherits the different Hashtable extends Dictionary,hashmap extends Abstractmap, but all implements the map interface

2. Whether the key value can be null: HashMap The key value is allowed to be null, Hashtable not

3. Security: Hashtable is a synchronized thread-safe, HashMap is not a thread-safe feature

4. Default Volume: Hashtable the default initial size is 11, and then expands to the original 2n+1 each time. HashMap The default initialization size is 16, and then expands to twice times the original.

Note: If you have already declared HashMap and want to achieve synchronization, you can pass Collections.synchronizedmap (map); Make security settings

, Concurrenthashmap is recommended in multithreaded environments. The difference between HashSet and HashMap.

Please click here to enter a picture description HASHMAP the underlying data structure.

HashMap interior is an array and linked list to achieve, through the key hash value found in the array position, and traverse the location of the list, find the key value of the same entry. The list in the HashMap consists of the entry class, entry contains three elements: Key,value and Next (refers to the down one entry), and the list in the HashMap adds a new entry, which is placed in the head position of the list, The new entry next element points to the original entry in the head of the list. Do you know how HashMap works?

HashMap the hash algorithm to determine the key in the map storage, and through the hash algorithm to increase the size of the collection. Hash table can store the location of the elements called barrels, if the hash value through the key to conflict, then the form of a linked list, to store elements. HashMap expansion is a time-consuming task, so if you can estimate the capacity of a map, it is best to give it a default initial value and avoid multiple expansions. Construction method

HASHMAP ()//non-parametric construction method

HashMap (int initialcapacity)//Specify initial capacity construction method
HashMap (int initialcapacity, float loadfactor)//Specify initial capacity and load factor
HashMap (map< extends K,? extends v> m)//specified set, converted to HashMap

HashMap provides four construction methods, which are executed by a third method, but the first three methods do not initialize the array, and the table that holds the array elements in Haspmap is still 0 when the constructor is invoked. The Inflatetable () method called in the fourth constructor completes the initialization of the table and adds the elements in M to the HashMap. Add method

 public v put (k key, v value)  {if  (table == empty_table)  { //whether inflatetable (threshold) is initialized, if  (key == null)  //is placed in position No. 0 return 
Putfornullkey (value); Int hash = hash (key);  //compute the hash value int i = indexfor (hash, table.length);   //calculates the storage location in entry[] 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);  //added to map return null; }
1 if the key is null, from the list in the Entry array table labeled 0,
Find out if the key is null or not, and if so, replace the entry value with the new value and return the old value;
If there is no entry with the key null, the modification number (Modcount) is added 1, and then a new entry is appended, the
key is null,value to the passed-in value, and the entry is placed in the table[0 position on the head of the list, and returns NULL.
2 If the key is not NULL, first get the hash value of the key, and through the hash to determine the Entry Array table index subscript i
to the table[i] position of the linked list loop traversal, Find out if the key value has the same entry (the hash value of the incoming key is
equal to the hash value of the entry, and the incoming key equals or equates to the entry key), and if it exists, replaces its value with the
new value and returns the old value;
The modification number (Modcount) is increased by 1, then a entry is added to the header of the corresponding list in table[i
and returns NULL.

AddEntry ()------Hash collision generation and solution

The storage index in the 
/* * hash hash value * key  key * value value value * bucketindex entry[] Array * /Void addentry (Int hash, k key, v value, int bucketindex)  
{if  ((size >= threshold)  &&  (null != table[bucketindex))  { Resize (2 * table.length);  //expansion operation, where the data elements are recalculated and placed in the newtable, and the order of the linked lists is the opposite of the previous order hash =  (null
 != key)  ? hash (key)  : 0;
Bucketindex = indexfor (hash, table.length);
} createentry (Hash, key, value, bucketindex);
} void createentry (Int hash, k key, v value, int bucketindex)  {
entry<k,v> e = table[bucketindex];
Table[bucketindex] = new entry<> (hash, key, value, e);
size++; }

Add to the specific operation of the method, before adding the capacity of the judge, if the current capacity reached the threshold, and need to be stored in the entry[] array, advanced expansion operation, empty capacity of the table length of twice times. The hash value is recalculated, and the location of the array is stored, and the order of the chain list is opposite to the list before the expansion. The newly added entry entity is then stored to the head of the current entry[] location list. Before 1.8, the newly inserted elements were placed in the head position of the linked list, but the operation was prone to deadlock in a highly concurrent environment, so after 1.8, the newly inserted elements were placed at the end of the list.

HashMap inside the bucket appeared in the form of a single linked list, the hash table to solve a problem is the hash value of the conflict, usually two methods: Linked list method and open address method. The list method is to organize the object of the same hash value into a slot with the hash value; The open address method is a detection algorithm that continues to look for the next available slot when a slot is already occupied.

The code for the above method is simple, but it contains a design: The system always puts the newly added Entry object into the Bucketindex index of the table array-if there is already a Entry object at the Bucketindex index, the newly added Entry object points to the original Entry object (produces a Entry chain), if there is no Entry object at Bucketindex Index, that is, the e variable of the above program code is NULL, that is, the newly placed Entry object points to null, which means that no Entry chain is generated. HashMap There is no hash conflict, not form a single linked list, HashMap lookup element quickly, get () method can directly navigate to elements, but a single linked list, a single bucket store is not a Entry, but a Entry chain, The system must iterate through each Entry in order until it finds the Entry to search for-if the Entry that is to be searched is at the very end of the Entry chain (the Entry was first placed in the bucket), the system must loop to the last to find the element. It is known from the above that if multiple hashcode () values fall into the same bucket, the values are stored in a list. In the worst case, all the keys are mapped to the same bucket, so the hashmap degenerate into a list-the lookup time from O (1) to O (n). In other words, we can solve this hash collision problem by the way of linked list.

Get method

 public v get (Object key)  {if  (key == null)//return value of table[0] 
Return getfornullkey ();
Entry<k,v> entry = getentry (key);
Return null == entry ? null : entry.getvalue (); } final entry<k,v> getentry (Object key)  {if  (size == 0)  {return
 null;
} int hash =  (Key == null)  ? 0 : hash (key); for  (Entry<k,v> e = table[indexfor (hash, table.length)]; e != null; E  = e.next)  {object k; if  (e.hash == hash && E.key)  == key | |
  (Key != null && key.equals (k))) return e;
} return null; }
If the incoming key (key) is null, the value in the list labeled 0 from the Entry array table is found and returned, and NULL is returned
if the Passed-in key (key) is not NULL, gets the hash value of the key
Gets the index subscript (H & (Length-1)) in the table array by hash value hash to iterate through the
entry linked list
of the index subscript in the table array This entry is the entry object to find if the hash of the key (key) passed in is equal to the hash value (hash) of the entry,
and if the key passed in is equal to (= =) or equivalent to (equals) the entry key.
, traversing the entry list if it has not been found, returns NULL to return the value of the entry object that was found
(value), and returns null without finding it

Delete method

Public v remove (Object key)  {Entry<k,v> e = removeentryforkey (key);
return  (E == null ? null : e.value); } final entry<k,v> removeentryforkey (Object key)  {if  (size == 0)  
{return null;}
int hash =  (Key == null)  ? 0 : hash (key);
Int i = indexfor (hash, table.length);
entry<k,v> prev = table[i];
entry<k,v> e = prev;
while  (e != null)  {entry<k,v> next = e.next;
object k; if  (e.hash == hash && (k = e.key)  == key | |   (Key != null && key.equals (k)))  {modcount++ size--if  (prev 
== e) table[i] = next;
else prev.next = next;
E.recordremoval (this);
return e;
} prev = e; E = next;
} return e;
 }

Delete operation, first calculate the hash value of the specified key, and then calculate the storage location in the table, determine whether the current position entry entity exists, if there is no direct return, if the current position has entry entity exists, then start traversing the list. Three entry references were defined, pre, E, next. In the loop traversal process, first determine whether the pre and e are equal, if the equality indicates that the table's current position has only one element, directly table[i] = next = null. If you form a connection between the pre-> e-> Next, determine if the key of E is equal to the specified key, and if equal, let the pre-> next and E lose the reference.
HASHMAP Traversal mode

Traversal of the HashMap key value pairs

Step one: Gets the set collection of the HashMap "key value pairs" based on EntrySet ().

Step two: Through the iterator iterator to traverse the "first step" of the collection

Suppose the map is a
string type for the key in the HashMap object/map, and value is an integer
integ = null;
Iterator iter = Map.entryset (). iterator ();
while (Iter.hasnext ()) {
Map.entry Entry = (map.entry) iter.next ();
Gets the key
key = (String) entry.getkey ();
Gets the value
Integ = (Integer) entry.getvalue ();

2. Traversing the HashMap key

Step one: Gets the set collection of the "keys" of the HashMap according to Keyset ().

Step two: Iterate through the "first step" of the collection through the iterator iterator.

Suppose the map is a
string type for the key in the HashMap object/map, and value is the integer type
string key = null;
Integer integ = null;
Iterator iter = Map.keyset (). iterator ();
while (Iter.hasnext ()) {
//get key
key = (String) iter.next ();
Gets the value
Integ = (Integer) map.get (key) according to key;

3. Traversing the value of HashMap

Step one: Gets the collection of HashMap's "values" based on value ().

Step two: Iterate through the "first step" of the collection through the iterator iterator.

Suppose the map is a
string type for the key in the HashMap object/map, and value is an integer of integer
value = null;
Collection C = map.values ();
Iterator iter= c.iterator ();
while (Iter.hasnext ()) {
value = (Integer) iter.next ();
}

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.