Loop enumeration bypass

What is the best way to loop through an enumeration.

I have an "Destination" enumeration, and I want to cycle through it. I have currently implemented the following method in an enumeration that returns the following value, I just wondered if there is a better way / built-in support for loopback.

current code

enum Direction { east, north, west, south; Direction next() { switch (this) { case east: return north; case north: return west; case west: return south; case south: return east; } return null; } } 
+4
source share
3 answers

Convert to int (via ordinal() ), loop and convert back to enumeration (via values[i] ).

Like this:

 Direction next() { return values()[(ordinal() + 1) % values().length]; } 
+6
source

It would be pretty simple to implement a circular Iterator :

 enum Direction implements Iterable<Direction> { east, north, west, south; @Override public Iterator<Direction> iterator() { return new DirectionIterator(); } class DirectionIterator implements Iterator<Direction> { Direction next = Direction.this; @Override public Direction next() { try { return next; } finally { next = values()[(next.ordinal() + 1) % values().length]; } } @Override public boolean hasNext() { return true; } @Override public void remove() { throw new NotImplementedException(); } } } 

Using:

 public static void main(String[] args) { Iterator<Direction> it = Direction.north.iterator(); for (int i = 0; i < 10; i++) System.out.println(it.next()); } 

Outputs:

 north west south east north west south east north west 
+8
source

You can use the fact that the enumeration values ​​assigned them integer values ​​for their cyclic transition.

+1
source

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


All Articles