How to find the value of an enumeration taking into account the arguments that were provided to its constructor?

I have an enumeration class as follows:

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 need a method: public static Position getPosition(int dx, int dy) Can I return Position.A1either Position.A2with data dxand dywithout using whole if-structures?

+3
source share
2 answers

Perhaps the easiest way (and actually relatively fast) is to simply scroll through the listings:

public static Position getPosition(int dx, int dy) {
    for (Position position : values()) {
        if (position.dx == dx && position.dy == dy) {
            return position;
        }
    }
    return null;
}
+7
source

You can save enums in Map(local to the enum class) as you create them. Fill the map with a key consisting of coordinates and a value representing an enumeration.

getPosition() (). , ( , )

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

( : , , .. )

0

Source: https://habr.com/ru/post/1711878/


All Articles