Amazon Interview Question
Software Engineer / DevelopersActaully I heard a presentation on Javassist and it could be used to modify the bytecode of a class at runtime. So we could actually modify the byte code of put method of Hashmap at runtime to insert the counting logic. More about Javassist; http://www.csg.is.titech.ac.jp/~chiba/javassist/
overriding.. hashcode() method and putting static variable inside it.
every time put() and get() call java will call hashcode() method to find hashcode()
hashcode() doesn't seem to be a good idea. Put and Get method of hashmap will call the key objects hashCode(); Hence it an overhead to override HashCode function in every key objects class. Imagine key being String class.
Cleaner way is to extend HashMap class and overide get, put call..and call super.put() and get method. Use get/put count per MyHashMap object.
When it comes to passing the MyHashMap to another method, reference would be created to same hashMap object. Hence continue to use the same get and put method.
Hence at the end . when you query MyHashmap objects getPutCount()/getGetCount() you should be getting the exact number of time the call was made to get/put method.
solution:
1) In case if map allows null keys then hashcode() of key doesn't get called. So hashcode() of key class can't be used for counting purpose. Hence Override will work as explained above. May be use decorator pattern.
2) How about implementing custom collection class called as MyHashMap which is very well supported by Java Collection Framework with the help of template such as AbstractMap etc.
What was your answer ?
- amit.h1b August 27, 2008