1
public enum Direction {
  UP,
  RIGHT,
  DOWN,
  LEFT,
}

i have two enum variables (a and b), in one case i have to check, if b is the next of a for example if a=UP and b=RIGHT. and also if a=left and b=UP. mabe something like this:

if(Direction.valueOf(a+1)==Direction.valueOf(b))

but when a=LEFT it would be out of bounds like an array right ?

2
  • 1
    yes, you'd need to manually wrap around Commented Nov 17, 2021 at 11:14
  • 1
    honestly I would not bother valueOf(). Just check their ordinal() with % Commented Nov 17, 2021 at 12:05

2 Answers 2

2

Try this.

public enum Direction {
    UP,
    RIGHT,
    DOWN,
    LEFT;
    
    private static final Direction[] VALUES = values();
    
    public Direction next() {
        return VALUES[(ordinal() + 1) % VALUES.length];
    }
  }

public static void main(String[] args) {
    Direction a = Direction.LEFT;
    Direction b = Direction.UP;
    System.out.println(a.next() == b);
}

output:

true
Sign up to request clarification or add additional context in comments.

Comments

1
if (b == Direction.values()[(a.ordinal() + 1) % Direction.values().length])

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.