给定提供给其构造函数的参数,如何找到枚举值?
我有一个像这样的枚举类:
public enum Position {
A1(0,0),
A2(1,0),
//etc
public final int dy, dx;
private Position(int dy, int dx) {
this.dy = dy;
this.dx = dx;
}
}
现在我想要一个方法:public static Position getPosition(int dx, int dy)
我可以使用给定的 dx
和 dy
返回 Position.A1
或 Position.A2
而无需使用大量if 结构?
I have an enum class like this:
public enum Position {
A1(0,0),
A2(1,0),
//etc
public final int dy, dx;
private Position(int dy, int dx) {
this.dy = dy;
this.dx = dx;
}
}
Now I want a method: public static Position getPosition(int dx, int dy)
Can I return Position.A1
or Position.A2
with the given dx
and dy
without using a whole lot of if-structures?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许最简单的方法(实际上相对较快)就是简单地循环枚举:
Perhaps the easiest way (and actually relatively fast) to do it is by simply looping through the enums:
您可以在创建枚举时将它们存储在
Map
(枚举类的本地)中。 使用由坐标组成的键和枚举本身的值填充地图。然后您的 getPosition() 方法将使用坐标作为存储值(枚举)的键。 这可能比迭代枚举集更快(通常这取决于创建的位置数量)
生成密钥的简单方法类似于
(注意:因为映射是静态的类,它是共享资源,您可能需要担心线程环境中的同步等问题)
You can store the enums in a
Map
(local to the enum class) as you create them. Populate the map with the key made up of the coordinates, and the value being the enum itself.Then your
getPosition()
method will use the coordinates as a key to the stored value (enum). That may be faster than iterating through the set of enums (as usual it depends on the number of positions created)A trivial way to generate the key would be something like
(note: since the map is static to the class, it's a shared resource and you may want to worry about synchronisation etc. in a threaded environment)