Tejas Sharma Tejas Sharma - 1 year ago 82
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?

Answer Source

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();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download