tags:

views:

341

answers:

2

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?

A: 

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

String key = "" + dx + "/" + dy;

(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)

Brian Agnew
That is a really bad way to create a key. Many times I've seen this sort of thing done, even when the key components could contain the separators.
Tom Hawtin - tackline
Well spotted. Done in haste. Now changed to actually work :-)
Brian Agnew
+3  A: 

Perhaps the easiest way (and actually relatively fast) to do it is by simply looping through the enums:

public static Position getPosition(int dx, int dy) {
    for (Position position : values()) {
        if (position.dx == dx && position.dy == dy) {
            return position;
        }
    }
    return null;
}
Tom Hawtin - tackline
thanks =) really useful!
Johannes