Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Nested enums appropriate in this case?

I have a requirement to support a number of ChartTypes. Each of these chart types can support a number of ChartSubTypes. For example AreaChart type can have PercentArea, StackedArea etc. I am thinking of using an Enum both for ChartTypes and SubTypes and then maintain a map somewhere which will be something like :

Map<ChartType,List<ChartSubTypes> mapTypes;

Can I somehow use a nested enum pattern here? If yes then how?

like image 576
Geek Avatar asked Mar 08 '13 07:03

Geek


2 Answers

If that definition is constant (i.e. You know which sub types can contain every type) You can use here enum definitions as follows

enum ChartSubTypes{
    PercentArea, StackedArea, ChartSubType3;
}

enum ChartTypes{
    AreaChart(ChartSubTypes.PercentArea, ChartSubTypes.StackedArea), 
    CharType2(ChartSubTypes.PercentArea, ChartSubTypes.ChartSubType3);

    private List<ChartSubTypes> subTypes = new ArrayList<ChartSubTypes>();

    private ChartTypes(ChartSubTypes ...chartSubTypes){
        for(ChartSubTypes subType : chartSubTypes){
            subTypes.add(subType);
        }
    }

    public List<ChartSubTypes> getSubTypes(){
        return Collections.unmodifiableList(subTypes);
    }
   }
like image 64
Arsen Alexanyan Avatar answered Nov 18 '22 04:11

Arsen Alexanyan


Yes, you can add the chart sub types to the chart type like thus:

public enum ChartType {
    AreaChart(SubChartType.PercentArea, SubChartType.StackedArea), 
    AnotherChart(SubChartType.PercentArea);

    private List<SubChartType> subChartTypes = new ArrayList<>();

    ChartType(SubChartType... subChartTypes) {
        Collections.addAll(this.subChartTypes, subChartTypes);
    } 

    public List<SubChartType> getSubChartTypes() {
        return this.subChartTypes;
    }

    public static Map<ChartType,List<SubChartType>> getMapTypes() {
        HashMap<ChartType,List<SubChartType>> mapTypes = new HashMap<>();
        for (ChartType chartType : values()) {
            mapTypes.put(chartType, chartType.getSubChartTypes());
        }
        return mapTypes;
    }
}

To get the map you wanted simply call ChartType.getMapTypes();.

If the requirement is that each ChartType should have one or more SubChartTypes then you will need this constructor to enforce that requirement.

ChartType(SubChartType requiredSubType, SubChartType... subChartTypes) {
    this.subChartTypes.add(requiredSubType);
    Collections.addAll(this.subChartTypes, subChartTypes);
} 

Varargs can have zero arguments.

like image 3
Lodewijk Bogaards Avatar answered Nov 18 '22 04:11

Lodewijk Bogaards