This question was asked to me in MS interview. I wanna know the exact design issue in this piece of code. Code was already given, needed to find the design issue.
I have class MyHashMap which extends java HashMap class. In MyHashMap class I have to keep some information of employees. Key in this map will be firstName+lastName+Address .
public MyHashMap extends HashMap<Object, Object> {
//some member variables
//
public void put(String firstName, String lastName, String Address, Object obj) {
String key = firstName + lastName+ Address;
put(key, obj);
}
public Object get(String firstName, String lastName, String Address) {
String key = firstName + lastName+ Address;
return get(key);
}
public void remove(Strig key) {
put(key, "");
}
//some more methods
}
What is wrong with this design? Should I subclass HashMap or should I declare
HashMap as member variable of this class? Or should I have implemented hashCode/equals methods?
There are quite a few problems, but the biggest problem I can see it that you’re using a concatenated
Stringas a key. The following two calls are different, but equivalent:There’s also an issue that you’re declaring that the key type as an
Object, but always usingStringand are therefore not taking advantage of the type safety that comes with generics. For example, if you wanted to loop through thekeySetof yourMap, you’d have to cast eachSetentry to aString, but you couldn’t be sure that someone didn’t abuse youMapby using anIntegerkey, for example.Personally, I would favour composition over inheritance unless you have a good reason not to. In your case,
MyHashMapis overloading the standardMapmethods ofput,getandremove, but not overriding any of them. You should inherit from a class in order to change its behaviour, but your implementation does not do this, so composition is a clear choice.To act as an example, overloading rather than overriding means that if you make the following declaration:
none of your declared methods will be available. As recommended by some of the other answers, it would be far better to use an object composed of firstName, lastName and address to act as your map key, but you must remember to implement
equalsandhashCode, otherwise your values will not be retrievable from theHashMap.