I want to create a finite state machine and most of the example code I can find uses enums and I was just wondering if it gives an advantage over just using a string or int to store the state.
With Enum:
class TrafficLight { enum State { RED, YELLOW, GREEN };
State state = State.GREEN;
public void iterate() throws InterruptedException {
switch (this.state) {
case RED:
System.out.println("RED");
Thread.sleep(1000);
this.state = State.GREEN;
break;
case GREEN:
System.out.println("GREEN");
Thread.sleep(1000);
this.state = State.YELLOW;
break;
case YELLOW:
System.out.println("YELLOW");
Thread.sleep(1000);
this.state = State.RED;
break;
}
}
public class Main {
public static void main(final String[] args) throws InterruptedException {
final TrafficLight a = new TrafficLight();
while (true) {
a.iterate();
}
}
}
With String
public class TrafficLight {
String state = "GREEN";
public void iterate() throws InterruptedException {
switch (state) {
case "RED":
System.out.println("RED");
Thread.sleep(1000);
state = "GREEN";
break;
case "GREEN":
System.out.println("GREEN");
Thread.sleep(1000);
state = "YELLOW";
break;
case "YELLOW":
System.out.println("YELLOW");
Thread.sleep(1000);
state = "RED";
break;
}
}
}
(Both use the same main method)
They both seem to be exactly the same to me I am just wondering if there are any cases in which enums are better or a string wouldn't work.
Thanks.