将特定字符串映射到常量整数?
给定一组特定的字符串,将它们映射到相应的整数组的最佳方法是什么?假设我有一个类,其中有一些内部使用的整数常量,但需要获取传入的外部字符串并确定它们映射到的正确对应的整数常量。
这是一个简化的示例:
public class Example {
public static final int ITEM_APPLE = 0;
public static final int ITEM_BANANA = 1;
public static final int ITEM_GRAPE = 3;
public void incomingData(String value) {
// Possible values would be "apple", "banana", and "grape" in this case.
}
}
从该值转换为其相应的整数常量的最合适方法是什么?哈希映射?或者有什么方法可以在静态成员中定义这些映射吗?另一个想法?
Given a specific set of strings, what's the best way to map them to a corresponding set of integers? Say I have a class with a few integer constants that I use internally, but need to take incoming external strings and determine the correct corresponding integer constant they map to.
Here's a simplified example:
public class Example {
public static final int ITEM_APPLE = 0;
public static final int ITEM_BANANA = 1;
public static final int ITEM_GRAPE = 3;
public void incomingData(String value) {
// Possible values would be "apple", "banana", and "grape" in this case.
}
}
What would the most appropriate approach be to go from that value to its corresponding integer constant? A HashMap? Or is ther any way to define these mappings in a static member? Another idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用 HashMap,因为它最接近您想要实现的目标,因此是一个可维护的解决方案。您可以定义静态 HashMap:
I would use a
HashMap
as that is closest to what you want to achieve, and therefore a maintainable solution. You can define a static HashMap:是的,使用
枚举
。您可以为每个枚举分配一个整数值,或者仅使用ordinal()
然后使用
ExampleEnum.valueOf("ITEM_APPLE").intValue()
将 String 解析为int
。如果 int 值是连续的并且从零开始,您可以完全删除
intValue
字段:只需使用
ExampleEnum.valueOf("ITEM_APPLE").ordinal()
Yes, use an
enum
. You can assign each enum an integer value, or just useordinal()
then use e.g.
ExampleEnum.valueOf("ITEM_APPLE").intValue()
to resolve String toint
.If the int values are sequential and zero-based, you can get rid of the
intValue
field altogether:and just use
ExampleEnum.valueOf("ITEM_APPLE").ordinal()
你“可以”使用反射,例如:
但是,你应该考虑使用枚举,或者如果没有太多可能性,只需使用一组
else if
语句...you 'could' use reflection eg:
however, you should consider using Enums or if there aren't too many possibilities just use a set of
else if
statements...我还建议使用 Enum 方法,尽管 ExampleEnum.valueOf("ITEM_APPLE").ordinal() 必须进行字符串比较才能得到答案,而 HashMap 会给你带来 O(1) 的复杂度。
可能是一个危险的想法,但只是为了好玩(这个怎么样):
您只需确保字符串值的哈希码不会冲突;-)
I also suggest an Enum method, although ExampleEnum.valueOf("ITEM_APPLE").ordinal() will have to do string comparisons to get to the answer while a HashMap will give you an O(1) complexity.
Probably a dangerous idea but just for fun (how about this):
You just have to ensure the string value's hash codes does not clash ;-)