循环遍历枚举

时间:2012-05-28 11:04:27

标签: java enums

循环遍历枚举的最佳方法是什么。

我有一个枚举方向,我想循环遍历它。目前我在枚举中实现了下一个返回下一个值的方法,我只是想知道是否有更好的方法/内置支持循环遍历。

当前代码

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;
    }
}

3 个答案:

答案 0 :(得分:8)

实现循环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();
        }
    }
}

用法:

public static void main(String[] args) {

    Iterator<Direction> it = Direction.north.iterator();

    for (int i = 0; i < 10; i++)
        System.out.println(it.next());
}

输出:

north
west
south
east
north
west
south
east
north
west

答案 1 :(得分:6)

转换为int(通过ordinal()),循环并转换回枚举(通过values[i])。

像这样:

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

答案 2 :(得分:1)

您可以使用枚举值为其分配整数值以循环它们的事实。

相关问题