The difference between hashmap and hashtable in Java.

Source: Internet
Author: User

Hashtable is widely used. hashmap is a class used to replace hashtable in the new framework. In other words, hashmap is recommended instead of hashtable. Maybe you think hashtable is very useful. Why not? Here we will briefly analyze their differences.

1. The hashtable method is synchronous, And the hashmap is not synchronized. Therefore, the difference between manual synchronization of hashmap in multithreading is like that of vector and arraylist.

You can check the source code of hashtable and find that except the constructor, all the public method declarations of hashtable have the synchronized keyword, while the source code of hashmap does not even have the shadow of synchronized. Of course, except for annotations.

2. hashtable does not allow null values (neither key nor value). hashmap allows null values (both key and value ).

First, let's look at an example of normal hashtable output:

[Java]
View plaincopyprint?
  1. Hashtable table = new hashtable ();
  2. Table. Put ("a-key", "a-value ");
  3. Table. Put ("B-key", "B-value ");
  4. Table. Put ("C-key", "C-value ");
Hashtable table = new Hashtable();table.put("a-key", "a-value");table.put("b-key", "b-value");table.put("c-key", "c-value");

The output is as follows:

[Java]
View plaincopyprint?
  1. A-key-a-Value
  2. C-key-C-Value
  3. B-key-B-Value
a-key - a-valuec-key - c-valueb-key - b-value

Let's look at another example of hashtable rejecting NULL:

[Java]
View plaincopyprint?
  1. Table. Put (null, "a-value ");
table.put(null, "a-value");

Exceptions after running are as follows:

[Java]
View plaincopyprint?
  1. Exception in thread "Main" Java. Lang. nullpointerexception
  2. At java. util. hashtable. Put (hashtable. Java: 399)
  3. At com. darkmi. sandbox. hashtabletest. Main (hashtabletest. Java: 20)
Exception in thread "main" java.lang.NullPointerExceptionat java.util.Hashtable.put(Hashtable.java:399)at com.darkmi.sandbox.HashtableTest.main(HashtableTest.java:20)

Hashmap example:

[Java]
View plaincopyprint?
  1. Hashmap map = new hashmap ();
  2. Map. Put (null, "a-value ");
  3. Map. Put ("B-key", null );
  4. Map. Put ("C-key", null );
HashMap map = new HashMap();map.put(null, "a-value");map.put("b-key", null);map.put("c-key", null);

 

After running, the output is as follows:

[Java]
View plaincopyprint?
  1. B-key-Null
  2. Null-a-Value
  3. C-key-Null
b-key - nullnull - a-valuec-key - null

 

PS: From the above example, we can find that hashtable is the same as hashmap: unordered storage.

3. The traversal methods of the two are similar. hashtable only has one more elements method than hashmap.

[Java]
View plaincopyprint?
  1. Enumeration em = table. Elements ();
  2. While (Em. hasmoreelements ()){
  3. String OBJ = (string) Em. nextelement ();
  4. System. Out. println (OBJ );
  5. }
Enumeration em = table.elements();while (em.hasMoreElements()) {String obj = (String) em.nextElement();System.out.println(obj); }

Hashtable and

Hashmap can return a collection using the values () method, and then traverse the collection:

[Java]
View plaincopyprint?
  1. Collection coll = map. Values ();
  2. Iterator it = Coll. iterator ();
  3. While (it. hasnext ()){
  4. String OBJ = (string) it. Next ();
  5. System. Out. println (OBJ );
  6. }
Collection coll = map.values();Iterator it = coll.iterator();while (it.hasNext()) {String obj = (String) it.next();System.out.println(obj);}

 

Both of them can also return a set through the entryset () method, and then traverse the process:

[Java]
View plaincopyprint?
  1. Set set = table. entryset ();
  2. Iterator it = set. iterator ();
  3. While (it. hasnext ()){
  4. Entry entry = (entry) it. Next ();
  5. System. Out. println (entry. getkey () + "-" + entry. getvalue ());
  6. }
Set set = table.entrySet();Iterator it = set.iterator();while (it.hasNext()) {Entry entry = (Entry) it.next();System.out.println(entry.getKey() + " - " + entry.getValue());}

 

4. hashtable uses enumeration and hashmap uses iterator

 

The following two points are compared from the internal implementation mechanism,

Learn more:

5. For different hash values, hashtable directly uses the hashcode of the object. The Code is as follows:

[Java]
View plaincopyprint?
  1. Int hash = key. hashcode ();
  2. Int Index = (hash & 0x7fffffff) % tab. length;
int hash = key.hashCode();int index = (hash & 0x7FFFFFFF) % tab.length;

 

Hashmap recalculates the hash value and replaces the modulo:

[Java]
View plaincopyprint?
  1. Int hash = hash (k );
  2. Int I = indexfor (hash, table. Length );
  3. Static int Hash (Object X ){
  4. Int H = x. hashcode ();
  5. H + = ~ (H <9 );
  6. H ^ = (H >>> 14 );
  7. H + = (H <4 );
  8. H ^ = (H >>> 10 );
  9. Return h;
  10. }
  11. Static int indexfor (int h, int length ){
  12. Return H & (length-1 );
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);

 

6. The default size of the hash array in hashtable is 11, and the increase is in the old * 2 + 1 mode. The default size of the hash array in hashmap is 16, and it must be an index of 2.

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.