Tejas Sharma Tejas Sharma - 2 months ago 7
Java Question

Switching between enum values in Java

forgive me if this is a stupid question, but I was wondering if enums in Java worked similarly to integers. What I mean is, say I had an enum declared as

public enum Colour {
BLACK, WHITE
}


Would I be able to switch between them the way I could switch between ints? Like

Colour newColour = !newColour;


Since as far as I am aware, they are basically ints in C. Is it similar at all?

Answer

Sure thing, you can achieve the same behavior by defining a toggle method inside your enum:

enum Colour {
    BLACK, WHITE;

    Colour toggle() {
        if (this.equals(BLACK))
            return WHITE;
        else
            return BLACK;
    }
}

The the usage is: Colour newColour = oldColour.toggle();

Comments