将java字符串高效地转换为等效的枚举 [英] Efficiently converting java string to its equivalent enum

查看:125
本文介绍了将java字符串高效地转换为等效的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串,我希望在不间断的时间内获得等价的枚举。
我有一个枚举类似于问题中显示的枚举。 创建字符串枚举的最佳方法

Given a string i want to get the enum equivalent of it in constant time. I have a enum defined like the one shown in the question. Best way to create enum of strings?

public enum Strings {
STRING_ONE("ONE"),
STRING_TWO("TWO")
;

private final String text;

/**
 * @param text
 */
private Strings(final String text) {
    this.text = text;
}

/* (non-Javadoc)
 * @see java.lang.Enum#toString()
 */
@Override
public String toString() {
    return text;
}
}

如果我现在得到一个字符串(比如说两个 ),有没有办法看看它是否存在,如果它存在,那么有一种方法我可以定义一个返回枚举值的方法(例如,如果我通过TWO,我应该回到Strings.STRING_TWO ?

If i now get a string (say "TWO"), is there a way to see if it exists and if it exists then is there a way i can define a method that will return the enum value (for example if i pass "TWO", i should be getting back "Strings.STRING_TWO"?

推荐答案

Enum.valueOf() 不够?你觉得如何更有效率?(通常)没有必要有一个枚举 STRING_ONE(ONE) - 只需调用枚举值 ONE ,您将获得 .valueOf()免费查找。

Is Enum.valueOf() not sufficient? How would you imagine being more efficient than that? There's (usually) no need to have an enum STRING_ONE("ONE") - just call enum value ONE and you get .valueOf() lookup for free.

否则,只需创建一个私有静态Map< String,YourEnum> 并提供类似的 valueOf()方法,查找地图

Otherwise, just create a private static Map<String, YourEnum> and provide a similar valueOf() method that looks up against the Map.

这篇关于将java字符串高效地转换为等效的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆