1

使用像这样的枚举,其中每个键都有多个值

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)

我认为,我基本上是在寻找这里描述的实现,但不同的是每个 ENUM 键(常量)都有几个值,我希望它可以getAbbreviation("long text 1")getAbbreviation("yet another one 2")...

是否有一种简单的方法可以遍历每个 ENUM(即ABBRn's)值字段,以填充巨大的地图,或者是否有更好的解决方案?

4

3 回答 3

2

每个枚举都有一个方法 values() 所以你可以这样做:

for(YourEnum type : values()){
        if(/*is Equal to Your descriptionText*/){
             return type;
        }
    }
    throw new IllegalArgumentException("No such BailiffPaymentStatus:"+dbRepresentation);
于 2014-10-13T10:55:59.503 回答
2

这依赖于枚举成员构造函数在静态初始化程序之前运行的事实。然后初始化器缓存成员及其长格式。

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
    }
}
于 2014-10-13T11:11:14.220 回答
1

我认为解决方案来自: cPu1 是在正确的轨道上。但是,当您使用这个问题的解决方案时,有一种更直接的方法来填充 HashMap。

  • 如何帮助 Netbeans Designer 加载使用 hashmap 的枚举反向查找的 JPanel-s?

        private static final Map<String, Abbreviation> abbreviationMap;
    
        private Abbreviation(String... longForms) {
            this.longForms = longForms;   //  optional
            mapAbbreviations( this, longForms )
        }
    
        private static void mapAbbreviations( final Status state, String... longForms ){
            if( null ==  abbreviationMap  ){
                abbreviationMap  = new HashMap( 20 );
            }
            for( String abbrev : longForms ){
                abbreviationMap.put( abbrev,  state );
            }
        }
    

此外,您实际上并不需要longFormstoString() 函数的私有字符串数组,因为无论如何所有值都与 Map 一起保存。

于 2017-05-22T02:45:41.060 回答