Tejas Sharma Tejas Sharma - 10 months ago 53
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 {

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?


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

enum Colour {

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

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