One of the mantras of object-oriented programming is that you should always favor composition over inheritance. However, it's always annoying when you want to implement Map but don't want to copy-paste-edit a bunch of methods that are just pass-through to the underlying map. This is code to do that, so I won't be tempted to just extend HashMap anymore.
private final Map<String,String> m_map = new HashMap<String,String>(); // begin Map impl public void clear(){ m_map.clear(); } public boolean containsKey(Object key){ return m_map.containsKey(key); } public boolean containsValue(Object value){ return m_map.containsValue(value); } public Set<Map.Entry<String,String>> entrySet(){ return m_map.entrySet(); } public boolean equals(Object o){ return m_map.equals(o); } public String get(Object key){ return m_map.get(key);} public int hashCode(){ return m_map.hashCode(); } public boolean isEmpty(){ return m_map.isEmpty(); } public Set<String> keySet(){ return m_map.keySet(); } public String put(String key, String value){ return m_map.put(key,value);} public void putAll(Map<? extends String,? extends String> m){ m_map.putAll(m) ;} public String remove(Object key){ return m_map.remove(key);} public int size(){ return m_map.size(); } public Collection<String> values(){ return m_map.values(); } // end Map impl
2 Comments
Here's an idea. You want to avoid repeating the duplication of that code, right? Because it's Java, the way to do that is to … use inheritance! That way you can create a CompositionHashMap to extend from. :D
It is a common mistake that one should *always* favour composition over inheritance. Inheritance can be abused but in many cases inheritance is better than composition.
Post a Comment