Skip to content

Java Map interface impl for composition

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

  1. 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

    Sunday, February 22, 2009 at 10:23 am | Permalink
  2. Christian wrote:

    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.

    Thursday, August 20, 2009 at 6:16 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*