Saturday, January 3, 2009

Custom Map Implementation in Java

Blogging after a long-long-long-... time :)

When we fetch records from HashMap, it gives records according to hash code, i.e. the records returned are not in the order when they're placed in the Map.

When we fetch records from TreeMap, it gives records in the sorted order of key, i.e. the records returned are not in the order when they're placed in the Map.

What I want was a Map that should return sequential values/objects that are put into when they're fetched. So, why not to make our own custom implementation of Map that does what is needed.

I constructed following Custom Map Implementation. Please find the code below:

CustomMapImpl.java



===
Supporting Class: CustomEntrySetImpl.java



===

Output of above program:

key1 : value1
key2 : value2
key4 : value4
key5 : value5
key6 : value6
key7 : value7

---

It was a very great experience. I also digged into the actual Java Map source code which was an amazing experience.


4 comments:

Anonymous said...

lol,so nice

Anonymous said...

Some of the content is very worthy of my drawing, I like your information!

Vishakh Bhat said...

Map doesn't allow duplicate keys , but in your custom Map duplicates keys are allowed which is wrong.

Atul Shinkar said...

Vishakh, you can treat this implementation as an example MultiValueMap.


_________________________________________________________________________________________________________________

"Look at the sky. We are not alone. The whole Universe is friendly to us and conspires only to give the best to those who dream and work."

- Dr. A P J Abdul Kalam
_________________________________________________________________________________________________________________