英文:
Should the HashMap<String,String> be refactored to Enum?
问题
我有一个地图,它表示了前缀名称与数据库中每个序列的序列名称之间的键名(组ID前缀)映射。例如,如果组ID为“GRP-MMM-PNL”,我应该获得该组的相应序列名称“mmm_panel_group_id”。我的问题是,我应该使用Enum来替代定义这个HashMap。
@AllArgsConstructor
public enum SequenceName {
mmm_panel_group_id("GRP-MMM-PNL-"),
mmm_service_group_id("GRP-MMM-SRV-"),
cms_panel_group_id("GRP-CMS-PNL-"),
cms_service_group_id("GRP-CMS-SRV-"),
smm_panel_group_id("GRP-SMM-PNL-"),
smm_service_group_id("GRP-SMM-SRV-");
@Getter
private String groupPrefix;
}
private static HashMap<String, String> getPrefixSequenceNameMap() {
HashMap<String, String> prefixSequenceNameMap = new HashMap<>();
prefixSequenceNameMap.put("GRP-MMM-PNL-", "mmm_panel_group_id");
prefixSequenceNameMap.put("GRP-MMM-SRV-", "mmm_service_group_id");
prefixSequenceNameMap.put("GRP-CMS-PNL-", "cms_panel_group_id");
prefixSequenceNameMap.put("GRP-CMS-SRV-", "cms_service_group_id");
prefixSequenceNameMap.put("GRP-SMM-PNL-", "smm_panel_group_id");
prefixSequenceNameMap.put("GRP-SMM-SRV-", "smm_service_group_id");
return prefixSequenceNameMap;
}
英文:
I have a map which represents the key name (group id prefix) mapping between prefixName and the sequence name of each sequence defined in the database. For example, if the groupId is "GRP-MMM-PNL", I should get the corresponding sequence name "mmm_panel_group_id" of that group. My question is should I use Enum instead of defining this HashMap.
@AllArgsConstructor
public enum SequenceName {
mmm_panel_group_id("GRP-MMM-PNL-"),
mmm_service_group_id("GRP-MMM-SRV-"),
cms_panel_group_id("GRP-CMS-PNL-"),
cms_service_group_id("GRP-CMS-SRV-"),
smm_panel_group_id("GRP-SMM-PNL-"),
smm_service_group_id("GRP-SMM-SRV-");
@Getter
private String groupPrefix;
}
private static HashMap<String, String> getPrefixSequenceNameMap() {
HashMap<String, String> prefixSequenceNameMap = new HashMap<>();
prefixSequenceNameMap.put("GRP-MMM-PNL-", "mmm_panel_group_id");
prefixSequenceNameMap.put("GRP-MMM-SRV-", "mmm_service_group_id");
prefixSequenceNameMap.put("GRP-CMS-PNL-", "cms_panel_group_id");
prefixSequenceNameMap.put("GRP-CMS-SRV-", "cms_service_group_id");
prefixSequenceNameMap.put("GRP-SMM-PNL-", "smm_panel_group_id");
prefixSequenceNameMap.put("GRP-SMM-SRV-", "smm_service_group_id");
return prefixSequenceNameMap;
}
答案1
得分: 1
没有所谓的“应该”。这取决于你的需求。
- 如果值在编译时已知且不会改变,枚举可能更好。不过你仍然可以使用 Map。
- 如果值只在运行时知道,或者在程序运行时发生变化,使用 Map。
英文:
There is no "should". It depends on what you want.
- If the values are known at compile-time and they do not change, an enum might be better. You can still use a Map though.
- If the values are only known at run-time or they change while the program is running, use a Map.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论