题
在所有我们的项目,我们有这样的枚举。他们工作得很好,但我们不知道他们。
特别与getDocumentType(String)方法。
有一种方法,以避免在所有枚举字段迭代?
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响应。她也没关系。
解决方案
您将不得不这样做迭代地方,由于写枚举的限制。在一个理想的世界,你会填充从DocumentType的构造函数中的静态地图,但是这是不允许的。
我可以建议在静态初始化执行一次迭代,并存储在查找表中的枚举的最佳:
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;
}
}
}
至少你不会做每一次迭代,但我怀疑你会看到任何有意义的性能改进。
其他提示
据我所知(对于它的价值),也就是做你想要的最好的方式。
这是我会怎么做至少
如果您enum
计数显著增长(几百 - 几千),你可能要添加Map
的Strings
ing到enums
做查找快一点。但是,对于你有eunums
的量小,这可能是矫枉过正。
如果字符串是在编译时已知,如果它们是有效的标识符,你可以用它们直接作为枚举的名称:
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;
}
看起来没什么问题。
我会离开迭代原样。当然,你可以一个地图<“标签”,“DocumentType”>的实施增加了枚举类,并做了查找,但它不会显著提高性能。
不隶属于 StackOverflow