The difference between Hashset,hashmap and Hashtable in Java

Source: Internet
Author: User
Tags rehash

The difference between HashMap, HashSet, and Hashtable is a common interview topic for Java programmers, which is only recorded in this blog and is thoroughly analyzed in the source code:

Before the analysis, the difference is listed below

1:hashset the bottom of the HashMap implementation, but there is no key-value, only the HashMap key set view, HashSet not allow duplicate objects

2:hashtable is based on the dictionary class, and HashMap is an implementation based on the map interface.

The default method in 3:hashtable is synchronous, while HashMap is non-synchronous, so Hashtable is multithreaded security

4:hashmap can be null as an entry for a table in key or Value,hashmap because the key cannot be duplicated, so only one record key can be null, and value can have more than one empty, but Hashtable does not allow null values (neither the key nor the value)

5: Memory Initial size is different, hashtable initial size is 11, and HashMap Initial size is 16

6: Memory expansion in a different way, Hashtable uses 2*old+1, and HashMap is 2*old.

7: The hash value is calculated differently, Hashtable directly uses the object's hashcode, and HashMap is on the basis of the object Hashcode also made some changes

Source Code Analysis:

For the difference 1, look at the following source code

Part of the HashSet class source code public  class hashset<e>      extends abstractset<e>      implements SET<E> Cloneable, java.io.Serializable  {   //For serialization of classes, can be used without its      static final long Serialversionuid =- 5024744406713321676L;      From here you can see that the HashSet class is really using HASHMAP to achieve the      private transient hashmap<e,object> map;        Dummy value to associate with a object in the backing Map      //This is the generation of an object that generates this object to associate the value of each key with this object to satisfy the HashMap key-value pair 
   private static Final Object PRESENT = new Object ();        /**      * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has      * Default initial Capac ity (+) and load factor (0.75).      /////Here is a constructor that constructs a HashMap object to hold the data public      HashSet () {      map = new hashmap<e,object> ();      }  

The conclusion from the above code is that HashSet is really implemented by HashMap, and that each key is the same object as the objects, so the value associated with the key is meaningless and the key is really meaningful. The keys in the HashMap are not allowed to repeat, so 1 is easy to understand.

For the difference 2, continue to look at the source code as follows

From here it can be seen that Hashtable is inherited from Dictionary, which implements the map interface public  class hashtable<k,v>      extends Dictionary<k,v >      implements Map<k,v>, Cloneable, java.io.Serializable {  //What can be seen here is that HashMap is inherited from the Abstractmap class, The map interface is implemented  //and therefore different from the parent class inherited by Hashtable, the public  class hashmap<k,v>      extends Abstractmap<k,v>      Implements Map<k,v>, Cloneable, Serializable  

Difference 3, find a targeted method to see, this method is put

Hashtable to the collective to increase the key-value pairs of methods, from here can be clearly seen is//using the Synchronized keyword, the role of this keyword is used for thread synchronization operation//So the following method for multithreading is safe, but this will affect efficiency  Public synchronized v put (K key, V value) {//makes sure the value is no null//If the value is NULL, an exception is thrown if (value = =      NULL) {throw new NullPointerException ();      }//makes sure the key is not already in the Hashtable.      Entry tab[] = table;      Get the key value of the hashcode, from here can also be seen key!=null, otherwise it will throw an unusual yo int hash = Key.hashcode ();      Gets the location of the hash table where the key is located int index = (hash & 0x7FFFFFFF)% Tab.length; As can be seen from the following cycle, the internal implementation uses a linked list, that is, a bucket structure for (entry<k,v> e = Tab[index]; e = null; e = e.next) {//if the Hasht                  When the same element is added in able, the value of the element is re-updated if (E.hash = = hash) && e.key.equals (key)) {V old = E.value;                  E.value = value;          return old;      }}//After the temporary use of it, probably means that the number of memory is less than a certain threshold, to reallocate memory modcount++; if (count >= threshold) {//Rehash the table If the threshold is exceeded rehash ();              tab = table;      Index = (hash & 0x7FFFFFFF)% Tab.length; The implementation in//hashmap is relatively simple, the following code//There is no synchronize keyword in the code here, it can be seen that this key function is not thread-safe public V put (K key, V value) {/          /For the key is empty, will be placed in the map value of a null-value composition of the key value pair//value is not empty processing, means that there can be more than one key, the key corresponding to the value of the element is empty.      if (key = = null) return Putfornullkey (value);          Calculates the position of the hash table where the key is located int hash = hash (Key.hashcode ());      int i = indexfor (hash, table.length); As can be seen from here is the list structure, using a bucket for (entry<k,v> e = table[i]; E! = null; e = e.next) {Object K              ; For the addition of the same key to the collective, it can be seen that it does not add in, but instead updates the operation if (E.hash = = Hash && (k = e.key) = = Key | | key.equals (k)                  ) {V oldValue = E.value;                  E.value = value;                  E.recordaccess (this);              return oldValue;   }}//start adding element modcount++;       AddEntry (hash, key, value, I);      return null;   }

  

The difference 4 in the above code, has been analyzed, you can take a closer look at

Difference 5 Memory Initial size is different, look at the source code of both:

Public Hashtable () {//     from here it can be seen that the default initialization size of 11, where 11 is not 11 bytes, but 11 entry, this entry is     //implements the key structure of the list     // The 0.75 here represents the load factor this  (one, 0.75f);   }  Here are some definitions   of public HashMap () {   //This default loading factor is also 0.75       this.loadfactor = default_load_factor;   The default acne is 0.75*16       threshold = (int) (default_initial_capacity * default_load_factor);   This starts with the default initialization size, where the size is       table = new Entry[default_initial_capacity];       Init ();   }  

  

From the above code, it can be seen that the default size of the two is different, one is 11, one is 16

Difference 6 Memory Expansion mode, look at the source code is also very clear, in fact, the difference is not big, see online a buddy wrote, said the two have a difference, in fact, really deep source, the difference is really small, one is 2*oldcapacity+1, one is 2*oldcapacity, you say big:)

Hashtable the function of adjusting memory, this function does not have synchronize keyword, but protected protected void rehash () {//Get the original table size int oldcapacity = TA      Ble.length;    entry[] Oldmap = table;      Set the new size to 2*oldcapacity+1 int newcapacity = oldcapacity * 2 + 1;    Open Space entry[] Newmap = new Entry[newcapacity];      The following will not be the tube ...      modcount++;      threshold = (int) (newcapacity * loadfactor);        Table = Newmap; for (int i = oldcapacity; i--> 0;) {for (entry<k,v> old = Oldmap[i]; old! = null;)          {entry<k,v> e = old;            Old = Old.next;          int index = (e.hash & 0x7FFFFFFF)% Newcapacity;          E.next = Newmap[index];          Newmap[index] = e;  }}}//hashmap it's a lot easier to see, you know, void addentry (int hash, K key, V value, int bucketindex) {entry<k,v> E =         Table[bucketindex];         Table[bucketindex] = new entry<k,v> (hash, key, value, E); If the threshold is exceeded if (size++ >= threshold)//the size is set to twice times the original            Resize (2 * table.length);   }

For the difference between the 7 hash value calculation method, the source, the same is no secret

Hashtable can be seen in the direct use of the keyword Hashcode as the hash value  int hash = Key.hashcode ();  Then perform modulo operations to find out where the uproar table is located   int index = (hash & 0x7FFFFFFF)% Tab.length;  The implementation in HashMap  //These two lines of code means to calculate the hashcode first, and then ask for it in the corresponding position of the hash table        int hash = hash (Key.hashcode ());  int i = indexfor (hash, table.length);  

The above HashMap can be seen in the key in two function hash and indexfor

The source code is as follows:

static int hash (int h) {      //This function ensures, hashcodes that differ-only to      //constant multiples at each Bit position has a bounded      //number of collisions (approximately 8 at default load factor).      I'm not going to say much about this,,>>>. This is an unsigned right-shift operator that can be interpreted as an unsigned integer      h ^= (H >>> a) ^ (h >>> N);      Return h ^ (H >>> 7) ^ (H >>> 4);  }  Position in the hash table   static int indexfor (int h, int length) {       return H & (LENGTH-1);   

SOURCE Link: http://www.cnblogs.com/ckwblogs/p/6019419.html

The difference between Hashset,hashmap and Hashtable in Java (RPM)

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.