带有这样的枚举,其中每个键都有多个值ABBR1("long text 1", "another description 1", "yet another one 1"),ABBR2("long text 2", "another description 2", "yet another one 2"),//and so on...如何通过调用类似getAbbreviation(descriptionText)的方法来反向查询缩写(常量)?我想,我基本上是在寻找一种here描述的实现,但是区别在于每个ENUM键(常量)都有几个值,我希望它既可以与getAbbreviation("long text 1")一起使用,也可以与 ...有没有一种简单的方法可以遍历每个ENUM(即getAbbreviation("yet another one 2"))的值字段,以填充一张巨大的地图,或者是否有更好的解决方案? (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 这依赖于枚举成员构造函数在静态初始化程序之前运行的事实。然后,初始化程序将缓存成员及其长格式。import java.util.Arrays;import java.util.HashMap;import java.util.Map;public enum Abbreviation { ABBR1("long text 1", "another description 1", "yet another one 1"), ABBR2("long text 2", "another description 2", "yet another one 2"); private static final Map<String, Abbreviation> ABBREVIATIONS = new HashMap<>(); private String[] longForms; private Abbreviation(String... longForms) { this.longForms = longForms; } public String toString () { return Arrays.toString(longForms); } static { for(Abbreviation abbr : values()) { for(String longForm : abbr.longForms) { ABBREVIATIONS.put(longForm, abbr); } } } public static Abbreviation of(String longForm) { Abbreviation abbreviation = ABBREVIATIONS.get(longForm); if(abbreviation == null) throw new IllegalArgumentException(longForm + " cannot be abbreviated"); return abbreviation; } public static void main(String[] args) { Abbreviation a = Abbreviation.of("yet another one 2"); System.out.println(a == Abbreviation.ABBR2); //true }} (adsbygoogle = window.adsbygoogle || []).push({});
10-07 20:27