Question

I have a class with a map (e.g. hashmap). The map values contain different elements which could have different types. My question is whether is better to implement if using different map with the same Keys; or using a nested class for encapsulate all the elements.

Pseudo-code example with nested class.

public class MyMap<T> {
    private class Element{
          int nElementA;
          int nElementB;
          double dbElementC;
    }

    private Map<T,Element> map = new HashMap<T,Element>();

    public int getElementA(T key) {return map.get(key).nElementA;}
    public int getElementB(T key) {return map.get(key).nElementB;}
    public double getElementC(T key) {return map.get(key).nElementC;}
}

Pseudo-code example with multiple maps.

public class MyMap<T> {
    private Map<T,Integer> mapA = new HashMap<T,Integer>();
    private Map<T,Integer> mapB = new HashMap<T,Integer>();
    private Map<T,Double> mapC = new HashMap<T,Double>();

    public int getElementA(T key) {return mapA.get(key);}
    public int getElementB(T key) {return mapB.get(key);}
    public double getElementC(T key) {return mapC.get(key);}
}

I think that nested class (especially private ones) can have negative effect on future code maintenance. However, I feel that I am wasting resources if I am using multiple maps with the same keys. Do I have any other alternative to reuse the map keys?

I was coding in Java when the problem arises, but I am also interesting in solutions for C++.

Was it helpful?

Solution

The main difference is not getting the elements but putting them. If the elements are related to each other, for instance Name, Age and Sex, encapsulating is better.

However, if they are tottaly different - which I think is not - you may use different maps.

My advice would be to make the class not private. A single line

map.put(Integer, new Element("John", 51, "Male"));

is better than

map1.put(Integer, "John");
map2.put(Integer, 51);
map3.put(Integer, "Male");

OTHER TIPS

It's a design decision, use the nested class solution only if make sense that the three elements can be encapsulate together under a single class. Take in account "high cohesion" when design your classes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top