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.



_________________________________________________________________________________________________________________

"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
_________________________________________________________________________________________________________________