I have the following code and I believe I see why I get the errors:
The errors are, for example:
- Self-reference in initializer in the constructor of
ROCK
atRPSGesture.ROCK
. - Illegal forward reference in the constructor of
ROCK
atRPSGesture.PAPER
.
public interface Gesture {
public List<? extends Gesture> winsFrom();
public List<? extends Gesture> tiesTo();
public List<? extends Gesture> losesTo();
}
public enum RPSGesture implements Gesture, Action {
ROCK(
Arrays.asList(RPSGesture.SCISSORS),
Arrays.asList(RPSGesture.ROCK),
Arrays.asList(RPSGesture.PAPER)
),
PAPER(
Arrays.asList(RPSGesture.ROCK),
Arrays.asList(RPSGesture.PAPER),
Arrays.asList(RPSGesture.SCISSORS)
),
SCISSORS(
Arrays.asList(RPSGesture.PAPER),
Arrays.asList(RPSGesture.SCISSORS),
Arrays.asList(RPSGesture.ROCK)
);
private final List<RPSGesture> winsFrom;
private final List<RPSGesture> tiesTo;
private final List<RPSGesture> losesTo;
private RPSGesture(final List<RPSGesture> winsFrom, final List<RPSGesture> tiesTo, final List<RPSGesture> losesTo) {
this.winsFrom = winsFrom;
this.tiesTo = tiesTo;
this.losesTo = losesTo;
}
@Override
public List<RPSGesture> winsFrom() {
return winsFrom;
}
@Override
public List<RPSGesture> tiesTo() {
return tiesTo;
}
@Override
public List<RPSGesture> losesTo() {
return losesTo;
}
}
I have seen Peter Lawrey's Answer, however is a static
initializer really the best way to do it? Are there any other reasonble alternatives?
Does the design of this enum look correct, or would you do it differently yourself? With hopefully less code in the class.