Differences between hashmap, hashtable, and hashset

Source: Internet
Author: User

Hashtable and hashmap:
Surface:
Hashtable does not allow null values (neither key nor value), and hashmap allows null values (both key and value ).
The hashtable method is synchronous, And the hashmap is not synchronized. Therefore, in multi-thread scenarios, the difference between manual synchronization of hashmap is similar to that of vector and arraylist.
Hashtable has a contains (object value), which has the same functions as containsvalue (object value.
Hashtable uses enumeration and hashmap uses iterator.
Internal:
In hashtable, the default size of the hash array is 11, and the increment is old * 2 + 1. The default size of the hash array in hashmap is 16, and it must be an index of 2.
Different hash values are used. hashtable directly uses the hashcode of the object. The Code is as follows:
Int hash = key. hashcode ();
Int Index = (hash & 0x7fffffff) % tab. length;
Hashmap recalculates the hash value and replaces the modulo:
Int hash = hash (k );
Int I = indexfor (hash, table. Length );
Static int Hash (Object X ){
Int H = x. hashcode ();
H + = ~ (H <9 );
H ^ = (H >>> 14 );
H + = (H <4 );
H ^ = (H >>> 10 );
Return h;
}
Static int indexfor (int h, int length ){
Return H & (length-1 );
}
Hashset and hashmap:
Hashmap can be viewed as three views: Key set, value collection, and entry set. Here, hashset is actually a view of hashmap. Hashset is implemented using hashmap internally. Unlike hashmap, it does not need two values: Key and value.

Inserting Objects into a hashset is actually just done internally.

Public Boolean add (Object O ){

Return map. Put (O, present) = NULL;
}

Inserting Objects into a hashset is actually just done internally.

Public Boolean add (Object O ){

Return map. Put (O, present) = NULL;
}

Hashmap is a hash ing. It is based on an implementation of hash table. It can insert elements in a constant time or find a group of key-value pair.

Hashset is a hash set, which determines the query time. All elements must have hashcode ()

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.