Java Implementation of HashMap

Source: Internet
Author: User

HashMap is one of the most frequently-used and important data structures. It provides dictionary operations, and the efficiency of Insert, Search, and Delete operations is high. This article will try to use Java to implement a simplest HashMap. Because of its simplicity, it is easy to see the true design idea of HashMap.

What is Hash?

In my understanding, Hash is the process of converting an object into a positive integer. The same object generates the same Hash Code, but the Hash Code of different objects is random, and different Hash codes are evenly distributed. Different objects may also share the same Hash Code, resulting in a collision.

Why Hash

Map stores key-value pairs in an array. Assume that the Key may be set to S. If the Key is not Hash, create an array with a size greater than or equal to S. length to store the Key. Otherwise, some keys may not be located to store data. When S is large and the data actually used is relatively small, it will cause a waste of space. Map S to a small set of R. Hash is used for such Mapping, but the obtained integer needs to be processed and the size is controlled within the R range.

Implementation

These operations include Insert, Put, Search, and Delete. The Hash process uses the hashcode () of the Object and also refers to the multiplication Hash algorithm in the introduction to algorithms. The linked list method is used to solve the collision. Pay attention to the next attribute of Node.

Public class HashMap
 
  
{Private static int DEFAULT_CAPACITY = 16; private static double A = (Math. pow (5, 0.5)-1)/2; private int capacity; private int size = 0; private Node
  
   
[] Buckets; public HashMap () {this (DEFAULT_CAPACITY) ;}@ SuppressWarnings ("unchecked") public HashMap (int capacity) {if (capacity <= 0) {throw new IllegalArgumentException ("capacity can not be negative or zero");} // ensure that capacity is 2 to the Npower int temp = 1; while (temp <capacity) {temp <= 2;} this. capacity = temp; buckets = new Node [this. capacity];} public void insert (K key, V value) {if (key = null) {throw new IllegalArgumentException ("key can not be null ");} int position = index (key); Node
   
    
Node = new Node
    
     
(Key, value); if (buckets [position]! = Null) {node. setNext (buckets [position]);} buckets [position] = node; size ++;} public void put (K key, V value) {if (key = null) {throw new IllegalArgumentException ("key can not be null");} int position = index (key); Node
     
      
Node = buckets [position]; while (node! = Null) {if (node. key. equals (key) {node. value = value; return;} node = node. next;} Node
      
        NewNode = new Node
       
         (Key, value); if (buckets [position]! = Null) {newNode. setNext (buckets [position]);} buckets [position] = newNode; size ++;} public void delete (K key) {if (key = null) {throw new IllegalArgumentException ("key can not be null");} int position = index (key); Node
        
          Node = buckets [position]; if (node = null) {return;} if (node. key. equals (key) {buckets [position] = node. next; size --;} while (node. next! = Null) {if (node. next. key. equals (key) {node. next = node. next. next; size --; break;} node = node. next ;}} public V search (K key) {if (key = null) {throw new IllegalArgumentException ("key can not be null ");} int position = index (key); Node
         
           Node = buckets [position]; while (node! = Null) {if (node. key. equals (key) {return node. value;} node = node. next;} return null;} public int size () {return size;} public boolean isEmpty () {return size = 0 ;}@ Overridepublic String toString () {StringBuffer buffer = new StringBuffer (); buffer. append ("{"); for (int I = 0; I <capacity; I ++) {Node
          
            Node = buckets [I]; while (node! = Null) {buffer. append (node. key + ":" + node. value + ","); node = node. next ;}} if (buffer. length ()> 1) {buffer. delete (buffer. length ()-2, buffer. length ();} buffer. append ("}"); return buffer. toString ();} private int index (K key) {int hashCode = key. hashCode (); double temp = hashCode * A; double digit = temp-Math. floor (temp); return (int) Math. floor (digit * capacity);} static class Node
           
             {Private final K key; private V value; private Node
            
              Next; public Node (K key, V value) {this. key = key; this. value = value;} public V getValue () {return value;} public void setValue (V value) {this. value = value;} public Node
             
               GetNext () {return next;} public void setNext (Node
              
                Next) {this. next = next;} public K getKey () {return key ;}} public static void main (String [] args) {HashMap
               
                 Map = new HashMap
                
                  (); Map. put ("001", "James"); map. put ("002", "Antony"); map. put ("003", "Bosh"); map. put ("004", "Wade"); map. put ("004", "WestBrook"); System. out. println (map); System. out. println (map. size (); System. out. println (map. search ("004 "));}}
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 

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.