'How to create enum method

I have this enum : public enum Color { RED, YELLOW; }. And I want to create a method that returns the opposite color of the actual one. So if I have RED, my method returns YELLOW. But I don't know the process to follow to do that. First step : public Color opposite() { return ??? }



Solution 1:[1]

If this element is RED, you want to return YELLOW; otherwise you want to return RED. So

public enum Color {
    RED, YELLOW;
    public Color opposite() {
        if (this==Color.RED) {
            return Color.YELLOW;
        }
        return Color.RED;
    }
}

The opposite() method can be written more concisely as:

public Color opposite() {
    return (this==Color.RED ? Color.YELLOW : Color.RED);
}

or, if you want to allow for more enum values, as:

public Color opposite() {
    switch (this) {
        case RED: return Color.YELLOW;
        case YELLOW: return Color.RED;
        // other possible values
    }
    // required for compiler
    return null;
}

As Holger suggests, Java 12 onwards supports switch expressions, which offer a cleaner alternative:

public Color opposite() {
    return switch (this) {
        case RED -> Color.YELLOW;
        case YELLOW -> Color.RED;
    };
}

Solution 2:[2]

Try using switch for this.

 public class Main {
    enum Color {
        RED,
        YELLOW;
    }
    public static void main(String[] args) {
    }
    public Color opposite() {
        Color myColor = Color.RED;
        return switch (myColor) {
            case RED -> Color.YELLOW;
            case YELLOW -> Color.RED;
        };
    }

}

If you prefer to use if statement instead of switch. You can try this instead

public Color opposite() {
        Color myColor = Color.RED;
        if (myColor == Color.RED) {
            return Color.YELLOW;
        } else  if (myColor == Color.YELLOW) {
            return Color.RED;
        }
        return null;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 marek