Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse enum?

I have an Enum class below

public class PTalkCommand {
public enum Code {
        CLR((byte) 0),
        ACK((byte) 170),
        SER((byte) 0),
        NAK((byte) 0),
        TIMEOUT((byte) 255),
        DIP((byte) 173),
        REQUEST_CHECKSUM((byte) 162),
        REQUEST_STATUS((byte) 181),
        REQUEST_FLASH((byte) 166),
        REQUEST_CONFIG_READ((byte) 249),
        REQUEST_STATUS_SCREEN((byte) 208),
        REQUEST_MULTIPULSE_CONFIG((byte) 0),
        REQUEST_SERIAL_NUMBER((byte) 62),
        REQUEST_BILL_NAMES((byte) 64),
        DO_FLASH((byte) 161),
        DO_MOTOR((byte) 81),
        DO_SEND_EE_PROM_DATA((byte) 50),
        DO_ENTER_FILE_NAME((byte) 61),
        DO_ENTER_SERIAL_NUMBER((byte) 63),
        DO_CONFIGURE((byte) 248),
        DO_MULTIPULSE_CONFIG((byte) 210),
        DATA_COLLECTION_RAW_SENSORS((byte) 84),
        DATA_COLLECTION_MODE((byte) 0),
        DATA_COLLECTION_CAL_POINTS((byte) 0),
        DATA_COLLECTION_WITH_DEBUG((byte) 68),
        DATA_COLLECTION_EXIT((byte) 119),
        CALIBRATE_OAS((byte) 150),
        CALIBRATE_NOTE_PRESENT_PUNCH((byte) 0),
        CALIBRATE_CB_REMOVED((byte) 0),
        CALIBRATE_IR_BLUE_TRANSMISSIVE((byte) 0),
        CALIBRATE_IR_REFLECTIVE((byte) 0),
        CALIBRATE_BLUE_REFLECTIVE((byte) 0),
        CALIBRATE_MONITOR_VOLTAGES((byte) 0),
        STACKER_OR_STACKERLESS((byte) 158),
        CALIBRATE_CURVE_LEVER((byte) 0),
        REQUEST_BEZEL_REV_LEV((byte) 73),
        DO_BEZEL_UPDATE((byte) 82);

        private final byte valueCode;

        private Code(byte value) {
            this.valueCode = value;
        }

        public byte getValue() {
            return valueCode;
        }
    }
}

And want it to get in reverse order. In .Net the code is like this

public void Prepend (PTalkCommand.Code[] commands) {
            IEnumerable<PTalkCommand.Code> enumerable = commands.Reverse<PTalkCommand.Code> ();
            foreach (PTalkCommand.Code current in enumerable) {
                base.Insert (0, (byte)current);
            }
        }

And in Java i am trying to do the same.

Enumeration<PTalkCommand.Code> enumerable = commands. ???????

But, i am not able to do it. Please tell me how can i do the same in Java?

like image 247
Vid Avatar asked Feb 27 '15 10:02

Vid


1 Answers

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
}
like image 55
Konstantin Yovkov Avatar answered Oct 07 '22 13:10

Konstantin Yovkov