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?
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With