The difference between Hashtable and HashMap

Source: Internet
Author: User
Tags rehash

Inherited parent classes are different:

* @since JDK1.0 */Publicclass hashtable<k,v>    extends dictionary<k,v>    implements Map<k,v>, cloneable, java.io.Serializable {

* @since 1.2 */public   class hashmap<k,v>    extends abstractmap<k,v>    implements map<k,v>, cloneable, serializable{

The initial array length is different:

 /**   * Constructs a new, empty hashtable WI     Th a default initial capacity (one) * and load factor (0.75).  */ public   Hashtable () { this  (one, 0.75f
   /**      * Constructs an empty <tt>HashMap</tt> with the default initial capacity     * (+) and the default L Oad factor (0.75).      */     Public HashMap () {        this. loadfactor = default_load_factor;          = (int) (default_initial_capacity * default_load_factor);         New entry[default_initial_capacity];        Init ();    }

Method is synchronous:
Whether the key can be null:hashmap, Hashtable can not
Value is not null,hashmap can be, Hashtable can not

   /*** Maps The specified <code>key</code> to the specified * <code>value</code> in this H Ashtable. Neither the key nor the * value can be <code>null</code>. <p> * The value can be retrieved by calling the <code>get</code> method * with a key that     is equal to the original key. *     * @paramKey The Hashtable key *@paramvalue The value *@returnthe previous value of the specified key in this hashtable, * or <code>null</code> if It did not have one *@exceptionNullPointerException If the key or value is * <code>null</code> *@seeobject#equals (Object) *@see#get (Object)*/     Public synchronizedv put (K key, V value) {//Make sure the value was not null    if( value ==NULL) {         throw new  nullpointerexception (); }    //makes sure the key is not already in the Hashtable.Entry tab[] =table; inthash = Key.hashcode (); intIndex = (hash & 0x7FFFFFFF)%tab.length;  for(entry<k,v> e = Tab[index]; E! =NULL; E =e.next) {if((E.hash = = hash) &&e.key.equals (Key)) {V old=E.value; E.value=value; returnOld ; }} Modcount++; if(Count >=threshold) {        //Rehash The table if the threshold is exceededrehash (); tab=table; Index= (hash & 0x7FFFFFFF)%tab.length; }    //creates the new entry.Entry<k,v> e =Tab[index]; Tab[index]=NewEntry<k,v>(hash, key, value, E); Count++; return NULL; }
HashMap:/*** Associates The specified value with the specified key on this map.     * If The map previously contained a mapping for the key, the old * value is replaced. *     * @paramkey key with which the specified value was to be associated *@paramvalue value to being associated with the specified key *@returnthe previous value associated with <tt>key</tt>, or * <tt>null</tt> if there is     No mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <TT>     ;null</tt> with <tt>key</tt>.) */     Publicv put (K key, V value) {if(Key = =NULL)             return  putfornullkey (value); inthash =Hash (Key.hashcode ()); inti =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))) {V OldValue=E.value; E.value=value; E.recordaccess ( This); returnOldValue; }} Modcount++;        AddEntry (hash, key, value, I); return NULL; }

HashTable:
if value is null, it will be thrown nullpointerexception/*** Returns A string representation of this <tt>Hashtable</tt> object * in the form of a set of ENT  Ries, enclosed in braces and separated * by the ASCII characters "<tt>,&nbsp;</tt>" (comma and space). Each * entry is rendered as the key, a equals sign <tt>=</tt>, and the * associated element, where T     He <tt>toString</tt> method is used to * convert the key and element to strings. *     * @returna string representation of this Hashtable*/     Public synchronizedString toString () {intmax = Size ()-1; if(max = =-1)        return"{}"; StringBuilder SB=NewStringBuilder (); Iterator<Map.Entry<K,V>> it =EntrySet (). iterator (); Sb.append (‘{‘);  for(inti = 0;; i++) {Map.entry<K,V> e =It.next (); K Key=E.getkey (); V value=E.getvalue (); Sb.append (Key== This? "(This Map)": Key.tostring ()); Sb.append (=); Sb.append (Value== This? "(This Map)": value.tostring ()); if(i = =max)returnSb.append ('} '). toString (); Sb.append (", "); }    }



The algorithm for calculating hash values for put and get is different:
Hashtable directly uses the value of the Hashcode () method;

HashMap:      Public v put (K key, V value) {        ifnull)            return  Putfornullkey ( value);         int hash = hash (Key.hashcode ());
HashMap:/*** Applies a supplemental hash function to a given hashcode, which * defends against poor quality hash functio  Ns.  This is critical * because HASHMAP uses power-of-two length hash tables, which * otherwise encounter collisions for Hashcodes that does not differ * in lower bits.     Note:null keys always maps to hash 0, thus index 0. */    Static intHashinth) {//This function ensures, hashcodes that differ//constant multiples at each bit position has a bounded//Number of collisions (approximately 8 at default load factor).H ^= (H >>>) ^ (H >>> 12); returnH ^ (H >>> 7) ^ (H >>> 4); }

HashTable: Public synchronizedv put (K key, V value) {//Make sure the value was not null    if(Value = =NULL) {        Throw NewNullPointerException (); }    //makes sure the key is not already in the Hashtable.Entry tab[] =table; inthash =Key.hashcode (); intIndex = (hash & 0x7FFFFFFF)% Tab.length;

The size of the expansion varies:

HashTable/*** Increases the capacity of and internally reorganizes this * hashtable, in order to accommodate and access I  TS entries more * efficiently.  This method was called automatically when the * number of keys in the Hashtable exceeds this Hashtable ' s capacity *     and load factor. */    protected voidrehash () {intOldcapacity =table.length; Entry[] Oldmap=table; intNewcapacity =oldcapacity * 2 + 1; Entry[] Newmap=NewEntry[newcapacity]; Modcount++; Threshold= (int) (Newcapacity *loadfactor); Table=Newmap;  for(inti = oldcapacity; i--> 0 ;) {         for(entry<k,v> old = oldmap[i];NULL ; ) {Entry<K,V> e =Old ; old=Old.next; intIndex = (e.hash & 0x7FFFFFFF)%newcapacity; E.next=Newmap[index]; Newmap[index]=e; }    }    }

HashMap/*** Adds A new entry with the specified key, value and hash code to * the specified bucket.     It is the responsibility of this * method to resize the table if appropriate.     * * Subclass overrides this to alter the behavior of put method. */    voidAddEntry (intHash, K key, V value,intBucketindex) {Entry<K,V> e =Table[bucketindex]; Table[bucketindex]=NewEntry<k,v>(hash, key, value, E); if(size++ >=threshold) Resize (2 * table.length); }

http://my.oschina.net/placeholder/blog/180069

http://blog.csdn.net/chenssy/article/details/22896871

The difference between Hashtable and HashMap

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.