dsjoka
dsjoka

Reputation: 61

enum duration question

So if we have an enum like:

  public enum light { red, yellow, green }

What would be the duration? Isn't it the time the light is a certain color?

Like

int duration = ligt.red = 1

or something like that?

Upvotes: 0

Views: 233

Answers (2)

adarshr
adarshr

Reputation: 62603

Declare your enum like this:

public enum Light { 
    RED(1), 
    YELLOW(2), 
    GREEN(3);

    private final int duration;

    Light(int duration) {
        this.duration = duration;
    } 

    public int getDuration() {
        return this.duration;
    }
}

Then you can use it like this:

public class Test {
    public static void main(String... args) {
        Light light = Light.RED;
        System.out.println("Duration of RED is: " + light.getDuration());
    }
}

EDIT: Based on Steve Kuo's suggestion, the variable duration has been made final.

Upvotes: 3

ILMTitan
ILMTitan

Reputation: 11037

Adarshr's answer presumes that duration is a property of the color of the light. If it is instead a property of the color at a particular set of signals, you might use an EnumMap<light, Integer>.

class Signal {
    private EnumMap<light, Integer> durations = new EnumMap<light, Integer>(light.class);
    Signal() {
        this.durations.put(light.red, 3);
        ....
    }
}

Upvotes: 0

Related Questions