Friday, April 7, 2017

Difference between HashMap and Hashtable In Java

In this post we will know the difference between HashMap and Hashtable. This is one of the frequently asked technical interview question for freshers.HashMap is not sorted or ordered. If you just need a Map,and you don't care about order of the elements while iterating through it,you can use a HashMap.The values can be null but the key should be unique.So you can have only one null value for key.

Hashtable is also same as HashMap which can store elements in the form of key-value pairs.HashTable is synchronized when using hash table you have to specify an object that is used as a key, and the value that you want to linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored with the table. Use H.T to store large amount of data, it will search as fast as vector. Hashtable store the data in sequential order.

How does a Hashtable internally maintains a key/value pairs:
The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

Let us see the differences between HashMap and Hashtable:


How to make HashMap synchronized:

By default HashMap object is not synchoronized but we can get synchronized version by using the following method of collection class
public static Map synchronizedMap(Map m1)

(or)

Collections.synchronizedMap(new HashMap());

Also Read:

Java for each loop example
Java HashMap with example
How to prepare for campus placements 
Every Entry software Developer should have know These things
Java program to find IP address of any website


No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...