Consider the following sscce
public enum Flippable A (Z), B (Y), Y (B), Z (A); private final Flippable opposite; private Flippable(Flippable opposite) { this.opposite = opposite; } public Flippable flip() { return opposite; } }
This does not compile because Z and Y were not declared as allowed arguments to constructor A and B
Potential Solution 1: Hardcoded Methods
public enum Flippable { A { public Flippable flip() { return Z; } }, B { public Flippable flip() { return Y; } }, Y { public Flippable flip() { return B; } }, Z { public Flippable flip() { return A; } }; public abstract Flippable flip(); }
While functional, it seems stylistically rather rude. Although I canβt say why this will be a real problem.
Potential Solution 2: Static Boot
public enum Flippable { A, B, Y, Z; private Flippable opposite; static { for(Flippable f : Flippable.values()) { switch(f) { case A: f.opposite = Z; break; case B: f.opposite = Y; break; case Y: f.opposite = B; break; case Z: f.opposite = A; break; } } } public Flippable flip() { return opposite; } }
This is even more rude than the first decision, because the field is no longer final and vulnerable to reflection. Ultimately, this is an obscure concern, but suggests a bad code smell.
Is there a way to do this, essentially the same as in the first example, but compiles correctly?
java enums self-reference
durron597
source share