Java interview question — explain the difference between HashMap and hashtable in detail

I The difference between HashMap and hashtable

Let's first look at the definitions of two classes

It can be seen that hashtable inherits from divisionary and HashMap inherits from abstractmap

The put method of hashtable is as follows

Note 1 the method is synchronous

Note 2 method does not allow value = = null

Note that method 3 calls the hashcode method of key. If key = = null, a null pointer exception will be thrown. The put method of HashMap is as follows

Note 1 the method is asynchronous

Note 2 the method allows key = = null

Note that 3 method does not make any call to value, so null is allowed

Supplement:

Hashtable has a contains method, which is easy to cause misunderstanding, so it has been removed from HashMap

Of course, both classes use containskey and containsvalue methods.

HashMap is a lightweight implementation of hashtable (non thread safe implementation). They have completed the map interface. The main difference is that HashMap allows null keys. Due to non thread safety, the efficiency may be higher than that of hashtable.

HashMap allows null as the key or value of an entry, while hashtable does not.

HashMap removes the contents method of hashtable and changes it to containsvalue and containskey. Because the contains method is easy to be misunderstood.

Hashtable inherits from the dictionary class, and HashMap is java 1 2 an implementation of the introduced map interface.

The biggest difference is that the hashtable method is synchronized, while the HashMap is not. When multiple threads access the hashtable, they do not need to synchronize their methods themselves, but the HashMap must provide external synchronization (collections. Synchronized map).

Hashtable and HashMap adopt the same hash / rehash algorithm, so the performance will not be very different.

Summary:

Key values in HashMap are allowed to be empty and asynchronous

The key value in hashtable cannot be empty. It is synchronous

Inheritance is different, but they all implement the map interface

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>