[JAVA] Verwenden Sie enum anstelle der int-Konstante

int enum Muster

Schlechte Ausdruckskraft. Übergabe von Apple an die Methode, die Orange erwartet Selbst wenn Sie Apple und Orange mit dem Operator == vergleichen, wird der Compiler nicht wütend.

public static final int APPLE_FUJI = 0;
public static final int APPLE_PIPIN = 1;
public static final int APPLE_GRANNY_SMITH = 2;

public static final int ORANGE_NAVEL = 0;
public static final int ORANGE_TEMPLE = 1;
public static final int ORANGE_BLOOD = 2;

Bei Verwendung von enum

public enum Apple {FUJI, PIPIN, GRANNY_SMITH}
public enum Orange {NAVEL, TEMPLE, BLOOD}

Aufzählungstyp zum Umschalten nach Wert

Im folgenden Code ist es technisch bis zum Ende der Methode erreichbar. Es gibt ein Problem wie das Vergessen, einen dem Schalter entsprechenden Fall hinzuzufügen

public enum Operation {
		PLUS, MINUS, TIMES, DIVID;

		//Führen Sie arithmetische Operationen durch, die durch Konstanten dargestellt werden
		public double apply(double x, double y) {
			switch(this) {
			case PLUS:
				return x + y;
			case MINUS :
				return x - y;
			case TIMES:
				return x * y;
			case DIVID:
				return x / y;
			}
			throw new AssertionError("Unknown op" + this);
		}
	}

Das Problem kann verbessert werden, indem eine abstrakte Methode definiert und die abstrakte Methode für jede Konstante überschrieben wird.

public enum Operation {
		PLUS {
			public double apply(double x, double y) {
				return x + y;
			}
		},
		MINUS {
			public double apply(double x, double y) {
				return x - y;
			}
		},
		TIMES {
			public double apply(double x, double y) {
				return x * y;
			}
		},
		DIVIDE {
			public double apply(double x, double y) {
				return x + y;
			}
		};
		public abstract double apply(double x, double y);
	}

Mit Lambda präziser auftragen


public enum Operation {
    PLUS((x, y) -> x + y),
    MINNUS((x, y) -> x - y),
    TIMES ((x, y) -> x * y),
    DIVIDE ((x, y) -> x / y);

    private final DoubleBinaryOperator op;

    Operation (DoubleBinaryOperator op) {
        this.op = op;
    }

    public double apply(double x, double y) {
        return op.applyAsDouble(x, y);
    }
}

Recommended Posts

Verwenden Sie enum anstelle der int-Konstante
Punkt 36: Verwenden Sie EnumSet anstelle von Bitfeldern
Punkt 37: Verwenden Sie EnumMap anstelle der ordinalen Indizierung
[Java] Warum StringUtils.isEmpty () anstelle von String.isEmpty () verwenden?
[Java] benutze Optional anstelle von if (hoge! = Null) {...}
Verwendung der Datumsklasse
[Swift] Warum FlowLayout Delegate anstelle von Instanz verwenden sollte
[Rails] Verwendung von Enum
[Rails] Verwendung von Enum
Verwenden Sie @ValueSource von ParametrisedTest von JUnit5