java hashmap - How to create your own HashMap?

How to create your own HashMap?

Posted on

java hashmap - How to create your own HashMap?Yesterday, whereas instructing java’s collections framework, One in every of my pupil ask me this query “Methods to create personal Hashmap? ”. I reply him verbally in regards to the code and idea, however couldn’t make any instance due to inadequate time. As we speak after discovering some spare time, I began writing my very own hashmap. Let’s see how we are able to write personal personal hashmap?

First, let’s take an outline of how hashtable works. Each entry has a key that has a hash code and a price. Keys have to be comparable in some trend. Many alternative keys can have the identical hash code, although in follow we wish this to are typically true solely of keys which can be additionally thought of equal.

Internally a hashtable shops a set of buckets, usually in a easy array. Every bucket comprises 0..N entries, every of which has a key and a price. To seek out what bucket an entry goes into we generate a numeric hashcode for the important thing, and decide what bucket index from hashcode mod the variety of buckets.

Let’s create an Entry class. We want a key, which might’t change, a price, which might change, and a pointer to subsequent so we are able to make our array that has 0..N entries in every spot. One thing like this could do it:

Now let’s create a HashMap class. The primary operation we’ll implement is get. We’ll have to establish what bucket to make use of, then cycle by way of the 0..N entries for that bucket to see if any of them have the precise key we’re excited by.

If there’s nothing in any respect within the bucket we are able to simply create a brand new entry and shove it in. If there’s already 1..N issues there we have to search by way of all of them. If we discover one with the very same key we’ll replace it, in any other case we’ll simply shove a brand new entry on the top.

Placing all of it collectively our remaining hashmap seems to be like this:

Following is a JUnit check case to confirm the functianality.

Supply techzoo.org