How to reverse enum?

前端 未结 2 1629
不知归路
不知归路 2021-01-13 16:51

I have an Enum class below

public class PTalkCommand {
public enum Code {
        CLR((byte) 0),
        ACK((byte) 170),
        SER((byte) 0),
        NAK         


        
相关标签:
2条回答
  • 2021-01-13 17:18

    You could add this inner class to your enum:

        public static class Backwards implements Iterable<Code> {
    
            @Override
            public Iterator<Code> iterator() {
                return new Iterator<Code>() {
                    private Code[] codes = Code.values();
                    private int i = codes.length - 1;
    
                    @Override
                    public boolean hasNext() {
                        return i >= 0;
                    }
    
                    @Override
                    public Code next() {
                        if (i < 0) {
                            throw new NoSuchElementException();
                        }
                        return codes[i--];
                    }
    
                };
            }
    
        }
    
    0 讨论(0)
  • 2021-01-13 17:35

    There's a built-in .values() method that returns an array of all the enum constants. You can iterate it backwards.

    Code[] values = Code.values();
    for (int i = values.length - 1; i >= 0; i--) {
        Code next = values[i];
        //do your thing
    }
    
    0 讨论(0)
提交回复
热议问题