5

在我们的整个项目中,我们都有这种枚举。它们工作得很好,但我们不确定它们。

特别是使用 getDocumentType(String) 方法。

有没有办法避免对所有 Enums 字段进行迭代?

public enum DocumentType {

    UNKNOWN("Unknown"),
    ANY("Any"),
    ASSET(Asset.class.getSimpleName()),
    MEDIA(Media.class.getSimpleName()),
    MEDIA35MM(Media.class.getSimpleName() + " 35mm");


    private String label;

    private DocumentType(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }

    public static DocumentType getDocumentType(String label){
        for(DocumentType documentType : DocumentType.values()){
            if(documentType.getLabel().equals(label)){
                return documentType;
            }
        }
        return UNKNOWN;
    }
}

编辑:检查 newacct 响应。她也很好。

4

4 回答 4

5

由于编写枚举的限制,您将不得不在某处进行该迭代。在理想情况下,您可以从 DocumentType 的构造函数中填充静态 Map,但这是不允许的。

我可以建议的最好的方法是在静态初始化程序中执行一次迭代,并将枚举存储在查找表中:

public enum DocumentType {

    .... existing enum stuff here

    private static final Map<String, DocumentType> typesByLabel = new HashMap<String, DocumentType>();
    static {
        for(DocumentType documentType : DocumentType.values()){
            typesByLabel.put(documentType.label, documentType);
        }
    }

    public static DocumentType getDocumentType(String label){
        if (typesByLabel.containsKey(label)) {
            return typesByLabel.get(label);
        } else {
            return UNKNOWN;
        }
    }
}

至少您不会每次都进行迭代,尽管我怀疑您会看到任何有意义的性能改进。

于 2009-07-29T12:38:51.357 回答
1

据我所知(对于它的价值),这是做你想做的最好的方式。

至少我会这样做。

如果您的计数enum显着增长(几百到几千),您可能需要添加一个to来更快地进行查找。但是对于你们中的一小部分人来说,这可能是矫枉过正。MapStringsenumseunums

于 2009-07-29T12:34:45.660 回答
1

在我看来很好。

我会保持原样迭代。当然,您可以将 Map<'label','DocumentType'> 实现添加到枚举类并进行查找,但这不会显着提高性能。

于 2009-07-29T12:34:54.147 回答
1

如果字符串在编译时是已知的,并且它们是有效的标识符,则可以直接将它们用作枚举的名称:

public enum DocumentType { Unknown, Any, Asset, Media, Media35mm }

然后得到它.valueOf()。例如:

String label = "Asset";
DocumentType doctype;
try {
    doctype = DocumentType.valueOf(label);
} catch (IllegalArgumentException e) {
    doctype = DocumentType.Unknown;
}
于 2009-07-29T18:46:58.140 回答